考虑一个典型的任务,当我们必须通过滚动数据库中的适当结果来构建大文件报告时。ORM 框架是Hibernate
. 我们知道,有 3 种方法可以避免OutOfMemoryException
这种模式:
使用
session.evict(...)
:ScrollableResults customers = session.createQuery("from Customers order by id").scroll(ScrollMode.FORWARD_ONLY); while (customers.next()) { Customer customer = (Customer) customers.get(0); addDataToReport(customer); session.evict(customer); }
使用
session.clear()
:ScrollableResults customers = session.createQuery("from Customers order by id").scroll(ScrollMode.FORWARD_ONLY); int i = 0; while (customers.next()) { Customer customer = (Customer) customers.get(0); addDataToReport(customer); if ( ++i % 1000 == 0) session.clear(); }
使用
CacheMode.IGNORE
:ScrollableResults customers = session.createQuery("from Customers order by id").setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY); while (customers.next()) { Customer customer = (Customer) customers.get(0); addDataToReport(customer); }
所以,问题是:对于上述目的,这些方法中哪一种更好(在性能方面)?或者可能有更有效的其他方法?