Reputation: 1516
I am new to java EJB and Hibernate and I have a problem with Hibernate Lazy Initalization of an entity. Basically I have and DAO which makes a DB call and I have 2 layer of services. So my question is why I am able to reach lazy fetched collections in the service just above the DAO layer but cannot access from the service which call second service before DAO.
public MyServiceClass {
public MyData myService(int id) {
MyEjbService myEjbService = new MyEjbService();
MyData mydata = myEjbService.getMyData(id);
return mydata; // here i cannot reach the collection object of the entity, lazy init exception
}
}
public MyEjbService
{
public MyData getMyData(int id){
MyDao myDao = new MyDao();
MyData myData = myDao.getData(id);
return myData; // here I can see and reach collection objects inside of the entity
}
}
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public MyDao{
@TransactionAttribute(TransactionAttribute.SUPPORT)
public MyData getData(int id){
...
}
}
Upvotes: 0
Views: 129
Reputation: 577
First, EJBs must be injected. Never create them with new() keyword. Use @Inject annotation for that. So in MyEjbService use @Inject for MyDao.
In MyServiceClass you are out of transaction boundary. You could use PersistenceContextType.EXTENDED, but better initialize all LAZY attributes in EJB directly (JOIN FETCH if attribute is lazy or annotate that attribute with FetchType.EAGER).
Upvotes: 1