2

In my Spring app i have Two entity:

@Entity
public class Category {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int id;
      ....
  @OneToOne
  @Cascade({CascadeType.ALL})
  @JoinColumn(name="page_id")
  private Page page;

  @OneToMany(fetch=FetchType.LAZY, mappedBy="category")
  private List<Shop> shop;

      ..getters and setters
 }

And

  @Entity
  public class Shop {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int id;
      ....

  @OneToOne(mappedBy="shop")
  private Settings settings;


  @ManyToOne
  @Cascade({CascadeType.SAVE_UPDATE})
  @JoinColumn(name = "category_id")
  private Category category;

  @OneToOne
  @Cascade({CascadeType.ALL})
  @JoinColumn(name = "page_id")
  private Page page;
      ...getters and setters

}

And in my test jUnit i added some category and some shop with this category, when i want to access to list of shops current category i have a error java.lang.NullPointerException ....

My test:

@ContextConfiguration(locations = {
    "classpath:security-context.xml",
    "classpath:dao-context.xml"
})
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=false)
@Transactional
public class CategoryTest { 

Shop shop1 = new Shop(....);
Shop shop1 = new Shop(....);
Category category1 = new Category(....);
Category category2 = new Category(....);

@Test
public void someTest(){
    shop1.setCategory(category1);
    shop2.setCategory(category2);
    shopService.add(shop1);
    shopService.add(shop2);
    assertEquals(2, shopService.getAllShop().size());
    assertEquals(2, categoryService.getAllShop().size());
      //IN THIS LINE I HAVE A ERROR
    assertEquals(1, categoryService.getCategory(category1.getId()).getShop().size());
   }
 }

For access to lazy atribute i added to my web.xml filtr: org.springframework.orm.hibernate3.support.OpenSessionInViewFilter This working properly in front app not in jUnit test.
Which point I make an error?

1 Answer 1

0

The lazy loading only takes place whist inside a transaction, when the session is open. So you get null in the test method unless you initialize the lazy loaded collection beforehand.

Another similar question

Sign up to request clarification or add additional context in comments.

1 Comment

I know that so i added org.springframework.orm.hibernate3.support.OpenSessionInViewFilter to my web.xml and added @Transactional annotation to my test class. But this not help. Am i wrong?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.