I keep on getting this error “Exception in thread “main” org.hibernate.LazyInitializationException: could not initialize proxy – the owning Session was closed” when I run the following code:
public ArrayList<ProfileDTO> getInitialProfiles(Contracts ct){
SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
Session session=sessionFactory.openSession();
Transaction tx=session.beginTransaction();
ArrayList<ProfileDTO> profileDTOs=new ArrayList<ProfileDTO>();
try{
Hibernate.initialize(ct);
SQLQuery query=session.createSQLQuery("select {b.*},{p.*},{t.*} from bidtool.bt_boiler_plates b,bidtool.bt_profile p,bidtool.bt_trade_lane t where b.contract_id=:val AND p.contract_id=:val AND t.contract_id=:val")
.addEntity("b",Boiler_Plates.class)
.addEntity("p",BidToolProfiles.class)
.addEntity("t",BidToolTradeLanes.class);
query.setParameter("val", ct.getContract_id());
List list=query.list();
Iterator iteContract = list.iterator();
while ( iteContract.hasNext() ) {
Object[] pair =(Object[]) iteContract.next();
Boiler_Plates bp=(Boiler_Plates)pair[0];
BidToolProfiles p=(BidToolProfiles)pair[1];
ProfileDTO profileDTO=new ProfileDTO();
profileDTO.setProfileId(p.getProfileId());
profileDTO.setBt_contracts(p.getBt_contracts());
profileDTO.setCreated(p.getCreated());
profileDTO.setProfileContent(p.getProfileContent());
profileDTO.setEditable(p.getEditable());
profileDTO.setProfileName(p.getProfileName());
profileDTOs.add(profileDTO);
}
return profileDTOs;
}
catch(Exception ex){
System.out.println(ex.getMessage());
return profileDTOs;
}
finally{
session.flush();
session.close();
}
}
It works fine whenever I don’t close the session but I cannot do that. I need to close the session. Your help will be appreciated. Thank you.
The error is raised when you access an association or a collection in an hibernate entity after the session has been closed. Looking at your code, I am guessing the problem probably lies in the following line:
profileDTO.setBt_contracts(p.getBt_contracts());when you try to access this collection elsewhere in your code, from within a different Session.
Try changing your query to:
select {b.*},{p.*},{t.*} from bidtool.bt_boiler_plates b,bidtool.bt_profile p,bidtool.bt_trade_lane t left join fetch p.bt_contracts btcontracts where b.contract_id=:val AND p.contract_id=:val AND t.contract_id=:valNotice that I have added a join fetch on the collection. This should make sure that the contracts collection is fetched at the same time the
BidToolProfilesentity is fetched. Also try initializing the collection before setting it in your DTO.