【发布时间】:2018-07-15 11:31:05
【问题描述】:
我正在使用JPA向数据库中插入很多对象(75.000),知道下面的代码可以多次调用...
由于我不希望内存泄漏,我要求 JPA 在 5.000 persist() 之后刷新 EntityManager。事实上,刷新并没有提交任何东西......
@Stateless
public class TwitterScheduler {
@EJB
private EntityUserFacade facade;
// ids are 5.000
public void do(ids) {
for (long id : ids.getIDs()) {
Entity e = new Entity();
e.set(...);
this.facade.create(e);
}
this.facade.getEntityManager().flush();
}
}
- 如果我用
@TransactionManagement(TransactionManagementType.BEAN)注释我的班级,如果我是对的,persist()将自动commit()交易。
但我担心性能/内存泄漏,我应该这样做吗?
我应该使用
@Resource UserTransaction utx;以某种方式加入到 JPA 的事务吗?如果有怎么办?因为我不能将事务管理设置为Container。我还想知道,如果我不刷新 EntityManager,我会出现内存泄漏。如果我使用
this.facade.getEntityManager().flush();刷新EntityManager,我越调用do()方法就会变得非常慢,为什么?
【问题讨论】:
-
flush() 刷新。它不承诺。 persist() 持续存在。它没有提交。如果您希望提交 5000 次插入,请确保调用您的方法并提交新事务:
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)