1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.imca.services;
17
18 import javax.persistence.EntityManager;
19 import javax.persistence.EntityManagerFactory;
20 import javax.persistence.EntityTransaction;
21 import javax.persistence.Persistence;
22
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25
26
27
28
29
30
31 public class Service {
32
33 private static EntityManagerFactory emf =
34 EntityManagerFactoryLazyHolder.emf;
35
36 protected EntityManager em;
37
38
39
40
41 private Log log = LogFactory.getLog(Service.class);
42
43
44
45
46 protected void startTransaction() {
47
48 if (log.isDebugEnabled()){
49 log.debug("Start Transaction for: " +
50 Thread.currentThread().getId());
51 }
52 em = emf.createEntityManager();
53 try {
54 em.getTransaction().begin();
55 } catch (Exception e1) {
56 try {
57 em.getTransaction().commit();
58 } catch (Exception e2) {
59 }
60 em.getTransaction().begin();
61 }
62 if (log.isDebugEnabled()) {
63 log.debug("Starting transation.");
64 }
65 }
66
67
68
69
70
71 protected void endTransaction() throws Exception {
72
73 if (log.isDebugEnabled()){
74 log.debug("End Transaction"+
75 Thread.currentThread().getId());
76 }
77
78
79 try {
80 em.getTransaction().commit();
81 } catch (Exception ex) {
82 log.error("Error while commiting transation: " +
83 ex.getMessage(), ex);
84 em.getTransaction().rollback();
85 throw ex;
86 }
87 if (log.isDebugEnabled()) {
88 log.debug("Transation ended.");
89 }
90 }
91
92 public void destroyEntityManager() {
93 if (emf != null) {
94 emf.close();
95 }
96 emf = null;
97 }
98
99 private static class EntityManagerFactoryLazyHolder {
100 private static EntityManagerFactory emf =
101 Persistence.createEntityManagerFactory("imca-persistence");
102 }
103 }