开发者

Hibernate: get rid of selected data stored in heap after reading it

I got this app that all it 开发者_运维问答does is perform selects and after I'm done reading that I no longer need the objects at all.

I got no problem reading the data, as the queries are very atomic. My problem is the big amount of data there, so eventually the old stored objects in heap lead to a out of memory exception.

How can I perform selects that get rid of the previous objects?


The object will be referenced by the NH session cache. To get rid of them, you could

  • Use the StatelessSession
  • Clear the session after the query (which also removes other objects from the session)
  • Evict each of the objects
  • Using a query that doesn't load entities, but values or dtos (select a, b or select new Dto(a, b)) which doesn't use the cache at all.


Objects that don't have references to them will be garbage collected and can't cause out of memory exceptions. So if you do get such exception then objects are still referenced and you need to find out what holds them.

If error is caused by too large result set, you could consider using pagination via setMaxResults() and setFirstResult() or Query.iterate().


After you are done working with the entity you queried, you should evict it from the Session cache and then dereference it, at which point, it will be eligible for garbage collection. See the examples in the section titled Managing the Caches of the Hibernate Guide. Here's an example:

ScrollableResult cats = sess.createQuery("from Cat as cat").scroll(); //a huge result set
while ( cats.next() ) {
    Cat cat = (Cat) cats.get(0);
    doSomethingWithACat(cat);
    sess.evict(cat);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜