How can I shorten a transaction in Spring using JPA?

I have this code:

run big query: Select all unprocessed objects from table A
for each result
    create or update an output object in table B
    update input object: Set it to "processed"

      

I would like to have a transaction over the body of the loop, that is, after processing one line of input, the updated objects must be committed, so when the program is interrupted, it will not process all the lines again, but will start from the faulty row.

I am using Spring 2.5, Hibernate 3.4 and JPA (i.e. has EntityManager

).

How can I do it? I tried to call em.getTransaction().commit()

in a loop, but Spring won't allow this.

+1


a source to share


4 answers


I would recommend looking at spring TransactionTemplate. The TransactionTemplate documentation contains examples that target exactly what you are trying to achieve.



+2


a source


Entity manager reads do not require a transaction. So I would try to refactor the internal method to update the row and set it up for a transaction. Note that this must be a public method using @transactional.



+1


a source


You have to work with a Hibernate session object.

Having an instance of javax.persistence.EntityManager ("em" I assume):

((org.hibernate.Session) em.getDelegate()).beginTransaction();

      

More information: https://www.hibernate.org/hib_docs/v3/api/org/hibernate/Session.html

0


a source


Without going through the spring docs and not knowing your transaction setup:

First you need to set up your transaction manager (probably HibernateTransactionManager). Then imho it is better to use spring TransactionTemplate to start each iteration inside its own transaction. You have to make sure that either the TransactionTemplate actually starts a new transaction, or the transaction does not start when you enter the method.

One tip: use the name of the transaction manager class as the log category for debugging transactions.

0


a source







All Articles