Ionut
Ionut

Reputation: 2858

JPA : multiple transactions

I'm trying to make 2 different DB calls with the same transaction entity. I know that I can make both interrogations between begin() and commit() but I'm trying this for educational purposes only.

EntityTransaction transaction = em.getTransaction();
EventService eventService = new EventService();
transaction.begin();
Event currentEvent = eventService.read(eventId);
transaction.commit();

if (currentEvent != null){
    CommentService commentService = new CommentService();
    transaction.begin();
    commentList = commentService.getList(1, id, 50);
    transaction.commit();
}

This piece of code throws :

Exception Description: Transaction is currently active

which is normal knowing that I'm attempting a begin() to an already opened transaction.

Is it correct to exclude the second transaction.begin() and just use commit() whenever I have to work with the DB?

LE: I'm using EclipseLink and RESOURCE_LOCAL

Upvotes: 3

Views: 5695

Answers (2)

Ionut
Ionut

Reputation: 2858

This happens because the transacton-type is set to RESOURCE_LOCAL. In this cases you must create some SingleTon classes which should handle the EntityManager and the EntityTransaction.

Upvotes: 2

James
James

Reputation: 18379

Odd. This should work. What JPA provider are you using? Perhaps enable logging to see what is going on.

Upvotes: 0

Related Questions