Why can’t I get value of entity object product.getName() loaded by id session.load(product.class,1) after method with @Transactional annotation returns? When I get product object in this way session.createQuery("from Product as product WHERE product.id = 1) everything is fine.
Edit
Dao method
public Product getProduct(Long id) {
return (Product) currentSession().load(Product.class, id);
}
Service method
@Transactional
public Product getProduct(Long id) {
return productDao.getProduct(id);
}
Controller method – it is supposed to send JSON but it breaks on product.getName() with error org.hibernate.LazyInitializationException: could not initialize proxy - no Session
@RequestMapping(value = "/product",headers="Accept=application/json")
public @ResponseBody Product getProduct() {
Product product = productService.getProduct(new Long(1));
System.out.println(product.getName());
return product;
}
A
LazyInitializationExceptionwill be thrown by Hibernate if an uninitialized collection or proxy is accessed outside of the scope of the Session, i.e., when the entity owning the collection or having the reference to the proxy is in the detached state.Sometimes a proxy or collection needs to be initialized before closing the Session. You can force initialization by calling
product.getName()or for example. However, this can be confusing to readers of the code and it is not convenient for generic code.The static methods
Hibernate.initialize()andHibernate.isInitialized(), provide the application with a convenient way of working with lazily initialized collections or proxies.Hibernate.initialize(product)will force the initialization of a proxy,product, as long as its Session is still open.You can also declare your some of fields to be eagely loaded