简体   繁体   中英

Hibernate get Collection from another session

Hi i've been getting the infamous "no session or session was closed" i know that is because i am trying to invke a collection of a hibernate persisted object in another session, so is there a way to actually do this without having to create the filter and add the JOIN fetch mode into it....

GRAVE: failed to lazily initialize a collection of role: ni.edu.uni.id.data.object.Curso.modulos, no session or session was closed org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: ni.edu.uni.id.data.object.Curso.modulos, no session or session was closed

This happens because the original session is closed. Before storing the item in memory, and prior to the Hibernate session being closed, you need to access any linked collections that will be used later on, so that it is loaded in memory. An alternative to this is to setup the collection such that it is Eager-loaded, however this might have performance implications.

Preloading a collection manually can easily be done by even accessing the .Count property (C#, but same applies for Java). Example:

Brand b = BrandRepository.GetById(1234);
int tmp = b.Products.Count; //this is only to load the products collection.  This can then be used in a later session.

It's better to refresh the persistent object. Eg call DAO getById() passing the id of the object and then use the necessary collection.

session.might可能会根据您的实际情况提供帮助

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM