1 package net.sumaris.core.test;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 import net.sf.ehcache.CacheManager;
29 import org.hibernate.Session;
30 import org.junit.After;
31 import org.junit.Before;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.springframework.beans.factory.annotation.Autowired;
35 import org.springframework.transaction.PlatformTransactionManager;
36 import org.springframework.transaction.TransactionStatus;
37
38 import javax.persistence.EntityManager;
39
40
41
42
43
44 public abstract class AbstractDaoTest {
45
46
47 private static final Logger log = LoggerFactory.getLogger(AbstractDaoTest.class);
48
49 private TransactionStatus status;
50
51 private boolean commitOnTearDown = true;
52
53 @Autowired
54 private PlatformTransactionManager transactionManager;
55
56 @Autowired
57 private EntityManager entityManager;
58
59 @Autowired(required = false)
60 protected CacheManager cacheManager;
61
62
63
64
65
66 @Before
67 public void setUp() throws Exception {
68 if (transactionManager != null) {
69 status = transactionManager.getTransaction(null);
70 if (log.isDebugEnabled()) {
71 log.debug("Transaction initialized");
72 }
73 }
74 }
75
76
77
78
79
80
81 @After
82 public void tearDown() throws Exception {
83 if (transactionManager != null) {
84 if (commitOnTearDown) {
85 transactionManager.commit(status);
86 } else {
87 transactionManager.rollback(status);
88 }
89 }
90
91 if (cacheManager != null) {
92 cacheManager.clearAll();
93 }
94 }
95
96
97
98
99
100
101 protected void setCommitOnTearDown(boolean commitOnTearDown) {
102 this.commitOnTearDown = commitOnTearDown;
103 }
104
105
106
107
108 protected void commit() {
109
110 transactionManager.commit(status);
111
112 status = transactionManager.getTransaction(null);
113 }
114
115
116
117
118
119
120 protected EntityManager getEntityManager() {
121 return entityManager;
122 }
123 }