Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 808
Michael Z Avatar asked Dec 27 '22 16:12

Michael Z


1 Answers

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++);
            }
        }
    );
}
like image 82
pap Avatar answered Dec 30 '22 10:12

pap