1 package de.campussource.cse.common.test;
2
3 import javax.persistence.EntityManager;
4 import javax.persistence.EntityManagerFactory;
5 import javax.persistence.EntityTransaction;
6 import javax.persistence.Persistence;
7
8 import org.junit.After;
9 import org.junit.Before;
10 import org.junit.BeforeClass;
11
12
13 public abstract class AbstractPersistentUnitTest {
14
15 protected static EntityManagerFactory entityManagerFactory;
16 protected EntityManager entityManager;
17 private AnnotationInjector injector;
18 private static long currentTimeMillis = System.currentTimeMillis();
19
20 @BeforeClass
21 public static void retrieveEntityManagerFactory() {
22 if (entityManagerFactory == null) {
23 entityManagerFactory = Persistence.createEntityManagerFactory("cseip-test");
24 }
25 }
26
27 @Before
28 public void retrieveEntityManager() {
29 entityManager = entityManagerFactory.createEntityManager();
30 }
31
32
33
34
35 @After
36 public void closeEntity() {
37 if (entityManager != null) {
38 EntityTransaction tx = entityManager.getTransaction();
39 if (tx.isActive()) {
40 tx.rollback();
41 }
42 entityManager.close();
43 }
44 }
45
46
47
48
49
50
51
52
53
54
55 protected void autowireByType(Object object) {
56 lazyInjectorInitialization();
57 injector.autowire(object);
58 }
59
60
61
62
63 private void lazyInjectorInitialization() {
64 if (injector == null) {
65 injector = new AnnotationInjector().defaultPersistentUnit(entityManager);
66 }
67 }
68
69
70
71
72 protected void txBegin() {
73 entityManager.getTransaction().begin();
74 }
75
76
77
78
79 protected void txCommit() {
80 entityManager.getTransaction().commit();
81 }
82
83
84
85
86 protected void commitAndBeginTx() {
87 txCommit();
88 txBegin();
89 }
90
91
92
93
94
95 protected Long uniqueId() {
96 return currentTimeMillis++;
97 }
98
99
100 }