View Javadoc

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  	 * Checks whether a active transaction exists. If so it will rollback this transaction.
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  //	Do not close factory to speed up tests!
47  //	@AfterClass
48  //	public static void closeFactory() {
49  //		if (entityManagerFactory != null) {
50  //			entityManagerFactory.close();
51  //		}
52  //	}
53  	
54  
55  	protected void autowireByType(Object object) {
56  		lazyInjectorInitialization();
57  		injector.autowire(object);
58  	}
59  
60  	/**
61  	 * Checks whether or not the Injector is already initialized or not. 
62  	 */
63  	private void lazyInjectorInitialization() {
64  		if (injector == null) {
65  			injector = new AnnotationInjector().defaultPersistentUnit(entityManager);
66  		}
67  	}
68  
69  	/**
70  	 * Start new transaction in current session
71  	 */
72  	protected void txBegin() {
73  		entityManager.getTransaction().begin();
74  	}
75  
76  	/**
77  	 * Commit current transaction in current session
78  	 */
79  	protected void txCommit() {
80  		entityManager.getTransaction().commit();
81  	}
82  
83  	/**
84  	 * Commit and begin new transaction in current session
85  	 */
86  	protected void commitAndBeginTx() {
87  		txCommit();
88  		txBegin();
89  	}
90  	
91  	/**
92  	 * Convenience method for creating a unique id
93  	 * @return unique id
94  	 */
95  	protected Long uniqueId() {
96  		return currentTimeMillis++;
97  	}
98  
99  
100 }