Initializing collections and proxies
A LazyInitializationException will be thrown by Hibernate if an uninitialized collection or proxy is accessed outside of the scope of the Session, ie. when the entity owning the collection or having the reference to the proxy is in the detached state. Sometimes we need to ensure that a proxy or collection is initialized before closing the Session. Of course, we can alway force initialization by calling cat.getSex() or cat.getKittens().size(), for example. But that is confusing to readers of the code and is not convenient for generic code. The static methods Hibernate.initialize() and Hibernate.isInitialized() provide the application with a convenient way of working with lazily initialized collections or proxies. Hibernate.initialize(cat) will force the initialization of a proxy, cat, as long as its Session is still open. Hibernate.initialize( cat.getKittens() ) has a similar effect for the collection of kittens. Another option is to keep the Session open until all needed collections and proxies have been loaded. In some application architectures, particularly where the code that accesses data using Hibernate, and the code that uses it are in different application layers or different physical processes, it can be a problem to ensure that the Session is open when a collection is initialized. There are two basic ways to deal with this issue:
Sometimes you don‘t want to initialize a large collection, but still need some information about it (like its size) or a subset of the data. You can use a collection filter to get the size of a collection without initializing it: ( (Integer) s.createFilter( collection, "select count(*)" ).list().get(0) ).intValue() The createFilter() method is also used to efficiently retrieve subsets of a collection without needing to initialize the whole collection: s.createFilter( lazyCollection, "").setFirstResult(0).setMaxResults(10).list(); |
|
来自: minwh > 《Hibernate》