Skip to content

Method: getTransaction()

1: /*
2: * JOPA
3: * Copyright (C) 2024 Czech Technical University in Prague
4: *
5: * This library is free software; you can redistribute it and/or
6: * modify it under the terms of the GNU Lesser General Public
7: * License as published by the Free Software Foundation; either
8: * version 3.0 of the License, or (at your option) any later version.
9: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public
16: * License along with this library.
17: */
18: package cz.cvut.kbss.jopa.transactions;
19:
20: import cz.cvut.kbss.jopa.exceptions.RollbackException;
21: import cz.cvut.kbss.jopa.model.AbstractEntityManager;
22: import cz.cvut.kbss.jopa.sessions.UnitOfWork;
23:
24: /**
25: * Wraps an {@link EntityTransaction} and mediates communication with the current persistence context and the {@link
26: * cz.cvut.kbss.jopa.model.EntityManager}.
27: */
28: public class EntityTransactionWrapper {
29:
30: private final AbstractEntityManager entityManager;
31: private EntityTransaction entityTransaction;
32: private UnitOfWork transactionUOW;
33:
34: public EntityTransactionWrapper(AbstractEntityManager entityManger) {
35: this.entityManager = entityManger;
36: }
37:
38: public EntityTransaction getTransaction() {
39:• if (entityTransaction == null) {
40: entityTransaction = new EntityTransactionImpl(this);
41: }
42: return entityTransaction;
43: }
44:
45: void begin() {
46: this.transactionUOW = entityManager.getCurrentPersistenceContext();
47: transactionUOW.begin();
48: entityManager.transactionStarted(entityTransaction);
49: }
50:
51: void commit() {
52: try {
53: transactionUOW.commit();
54: } catch (RuntimeException e) {
55: rollback();
56: throw new RollbackException(e);
57: }
58: }
59:
60: void transactionFinished() {
61: entityManager.transactionFinished(entityTransaction);
62: this.transactionUOW = null;
63: }
64:
65: void rollback() {
66: entityManager.removeCurrentPersistenceContext();
67: }
68: }