Search code examples
springhibernatejpatransactionstransactional

Commit during transaction in @Transactional


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?


Solution

  • 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++);
                }
            }
        );
    }