当我们必须通过从DB滚动适当的结果来构建大型文件报告时,考虑一个典型的任务。 ORM框架是Hibernate
。
我们知道,有三种方法,如何避免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);
}
所以,问题是:出于上述目的,哪种方法最好(在性能方面)?或者可能有更有效的其他方法?
答案 0 :(得分:4)
CacheMode.IGNORE
与您的问题无关。它是关于二级缓存,而不是会话缓存。evict()
或CascadeType.DETACH
的情况下配置关系,则CascadeType.ALL
不会驱逐相关实体。这意味着:
clear()
的方法是最佳选择: