1 |
|
|
2 |
|
|
3 |
|
|
4 |
|
|
5 |
|
|
6 |
|
|
7 |
|
|
8 |
|
|
9 |
|
|
10 |
|
|
11 |
|
|
12 |
|
|
13 |
|
|
14 |
|
|
15 |
|
|
16 |
|
|
17 |
|
package org.apache.camel.component.jpa; |
18 |
|
|
19 |
|
import javax.persistence.EntityManager; |
20 |
|
import javax.persistence.EntityManagerFactory; |
21 |
|
import javax.persistence.EntityTransaction; |
22 |
|
|
23 |
|
import org.apache.camel.impl.ServiceSupport; |
24 |
|
|
25 |
|
import org.springframework.orm.jpa.JpaCallback; |
26 |
|
|
27 |
|
import static org.apache.camel.util.ObjectHelper.notNull; |
28 |
|
|
29 |
|
|
30 |
|
|
31 |
|
|
32 |
|
public class DefaultTransactionStrategy extends ServiceSupport implements TransactionStrategy { |
33 |
|
private EntityManagerFactory entityManagerFactory; |
34 |
|
private EntityManager entityManager; |
35 |
|
|
36 |
0 |
public DefaultTransactionStrategy(EntityManagerFactory entityManagerFactory) { |
37 |
0 |
notNull(entityManagerFactory, "entityManagerFactory"); |
38 |
0 |
this.entityManagerFactory = entityManagerFactory; |
39 |
0 |
} |
40 |
|
|
41 |
0 |
public DefaultTransactionStrategy(EntityManager entityManager) { |
42 |
0 |
notNull(entityManager, "entityManager"); |
43 |
0 |
this.entityManager = entityManager; |
44 |
0 |
} |
45 |
|
|
46 |
|
public Object execute(JpaCallback callback) { |
47 |
0 |
EntityManager em = getEntityManager(); |
48 |
0 |
EntityTransaction transaction = em.getTransaction(); |
49 |
0 |
transaction.begin(); |
50 |
|
|
51 |
|
try { |
52 |
0 |
Object answer = callback.doInJpa(em); |
53 |
0 |
transaction.commit(); |
54 |
0 |
return answer; |
55 |
0 |
} catch (RuntimeException e) { |
56 |
0 |
if (transaction != null) { |
57 |
0 |
transaction.rollback(); |
58 |
|
} |
59 |
0 |
throw e; |
60 |
|
} |
61 |
|
} |
62 |
|
|
63 |
|
public EntityManager getEntityManager() { |
64 |
0 |
if (entityManager == null) { |
65 |
0 |
entityManager = entityManagerFactory.createEntityManager(); |
66 |
|
} |
67 |
0 |
return entityManager; |
68 |
|
} |
69 |
|
|
70 |
|
protected void doStart() throws Exception { |
71 |
|
|
72 |
0 |
getEntityManager(); |
73 |
0 |
} |
74 |
|
|
75 |
|
protected void doStop() throws Exception { |
76 |
0 |
if (entityManager != null) { |
77 |
0 |
entityManager.close(); |
78 |
|
} |
79 |
0 |
} |
80 |
|
} |