1 | package eu.clarin.cmdi.virtualcollectionregistry; |
---|
2 | |
---|
3 | import java.util.Map; |
---|
4 | |
---|
5 | import javax.persistence.EntityManager; |
---|
6 | import javax.persistence.EntityManagerFactory; |
---|
7 | import javax.persistence.EntityTransaction; |
---|
8 | import javax.persistence.Persistence; |
---|
9 | |
---|
10 | import org.slf4j.Logger; |
---|
11 | import org.slf4j.LoggerFactory; |
---|
12 | |
---|
13 | public class DataStore { |
---|
14 | private class ThreadLocalEntityManager extends ThreadLocal<EntityManager> { |
---|
15 | protected EntityManager initialValue() { |
---|
16 | if (emf == null) { |
---|
17 | throw new InternalError("JPA not initalizied correctly"); |
---|
18 | } |
---|
19 | return emf.createEntityManager(); |
---|
20 | } |
---|
21 | } // inner class ThreadLocalEntityManager |
---|
22 | private static final Logger logger = |
---|
23 | LoggerFactory.getLogger(DataStore.class); |
---|
24 | private final EntityManagerFactory emf; |
---|
25 | private final ThreadLocalEntityManager em = new ThreadLocalEntityManager(); |
---|
26 | |
---|
27 | DataStore(Map<String, String> config) |
---|
28 | throws VirtualCollectionRegistryException { |
---|
29 | try { |
---|
30 | emf = Persistence.createEntityManagerFactory( |
---|
31 | "VirtualCollectionStore", config); |
---|
32 | } catch (Exception e) { |
---|
33 | logger.error("error initializing data store", e); |
---|
34 | throw new VirtualCollectionRegistryException("error initializing", |
---|
35 | e); |
---|
36 | } |
---|
37 | logger.debug("data store was successfully initialized"); |
---|
38 | } |
---|
39 | |
---|
40 | public void destroy() throws VirtualCollectionRegistryException { |
---|
41 | if (emf != null) { |
---|
42 | emf.close(); |
---|
43 | } |
---|
44 | } |
---|
45 | |
---|
46 | public EntityManager getEntityManager() { |
---|
47 | return em.get(); |
---|
48 | } |
---|
49 | |
---|
50 | public void closeEntityManager() { |
---|
51 | EntityManager manager = em.get(); |
---|
52 | if (manager != null) { |
---|
53 | em.remove(); |
---|
54 | EntityTransaction tx = manager.getTransaction(); |
---|
55 | if (tx.isActive()) { |
---|
56 | tx.rollback(); |
---|
57 | } |
---|
58 | manager.close(); |
---|
59 | } |
---|
60 | } |
---|
61 | |
---|
62 | } // class DataStore |
---|