在@Transactional事务中提交(Commit during transaction in @Transactional)

是否可以在标记为Spring的@Transactional的方法中执行提交?

@PersistenceContext private EntityManager em; @Transactional(propagation = Propagation.REQUIRED) public void saveMembersWithMultipleCommits(List<Member> members) throws HibernateException { Iterator<Member> it = members.iterator(); while (it.hasNext()) { while (it.hasNext()) { Member wsBean = it.next(); em.persist(wsBean); // overall commit will be made after method exit log.info("Webservices record " + wsBean + " saved. " + i++); } } }

我想说每500个项目之后提交数据库。 上述情况可能吗?

Is that possible to perform commit in the method that is marked as Spring's @Transactional?

@PersistenceContext private EntityManager em; @Transactional(propagation = Propagation.REQUIRED) public void saveMembersWithMultipleCommits(List<Member> members) throws HibernateException { Iterator<Member> it = members.iterator(); while (it.hasNext()) { while (it.hasNext()) { Member wsBean = it.next(); em.persist(wsBean); // overall commit will be made after method exit log.info("Webservices record " + wsBean + " saved. " + i++); } } }

I would like to have commit to DB after say each 500 items. Is that possible with aforementioned context?

最满意答案

不,您需要使用例如TransactionTemplate API以编程方式执行此操作。 在这里阅读更多。

它看起来像

while (it.hasNext()) { transactionTemplate.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { int counter = 0; while (it.hasNext() && counter++ < 500) { Member wsBean = it.next(); em.persist(wsBean); log.info("Webservices record " + wsBean + " saved. " + i++); } } ); }

No, you need to do it programatically using, for instance, the TransactionTemplate API. Read more here.

It would look something like

while (it.hasNext()) { transactionTemplate.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { int counter = 0; while (it.hasNext() && counter++ < 500) { Member wsBean = it.next(); em.persist(wsBean); log.info("Webservices record " + wsBean + " saved. " + i++); } } ); }

更多推荐