01: package org.compass.gps.device.jpa;
02:
03: import javax.persistence.EntityTransaction;
04: import javax.persistence.PersistenceException;
05:
06: /**
07: * The default {@link EntityManagerWrapper} implementation. Works well both in
08: * JTA and Resource Local JPA transactions.
09: *
10: * @author kimchy
11: */
12: public class DefaultEntityManagerWrapper extends
13: AbstractEntityManagerWrapper {
14:
15: private boolean isJta;
16:
17: private EntityTransaction transaction;
18:
19: @Override
20: protected void beginTransaction() throws PersistenceException {
21: try {
22: // getTransaction will throw IllegalStateException if it is witin JTA
23: transaction = entityManager.getTransaction();
24: isJta = false;
25: try {
26: transaction.begin();
27: } catch (Exception e) {
28: transaction = null;
29: }
30: } catch (IllegalStateException e) {
31: // thrown when we are in a JTA transaction
32: isJta = true;
33: entityManager.joinTransaction();
34: }
35: }
36:
37: @Override
38: protected void commitTransaction() throws PersistenceException {
39: if (transaction == null) {
40: return;
41: }
42: try {
43: transaction.commit();
44: } finally {
45: transaction = null;
46: }
47: }
48:
49: @Override
50: protected void rollbackTransaction() throws PersistenceException {
51: if (transaction == null) {
52: return;
53: }
54: try {
55: transaction.rollback();
56: } finally {
57: transaction = null;
58: }
59: }
60:
61: @Override
62: protected boolean shouldCloseEntityManager() {
63: return !isJta;
64: }
65: }
|