1 |
|
|
2 |
|
|
3 |
|
|
4 |
|
|
5 |
|
|
6 |
|
|
7 |
|
|
8 |
|
|
9 |
|
|
10 |
|
|
11 |
|
|
12 |
|
|
13 |
|
|
14 |
|
|
15 |
|
|
16 |
|
|
17 |
|
|
18 |
|
package org.apache.camel.component.jpa; |
19 |
|
|
20 |
|
import org.apache.camel.impl.ServiceSupport; |
21 |
|
import static org.apache.camel.util.ObjectHelper.notNull; |
22 |
|
import org.springframework.orm.jpa.JpaCallback; |
23 |
|
|
24 |
|
import javax.persistence.EntityManager; |
25 |
|
import javax.persistence.EntityManagerFactory; |
26 |
|
import javax.persistence.EntityTransaction; |
27 |
|
|
28 |
|
|
29 |
|
|
30 |
|
|
31 |
|
public class DefaultTransactionStrategy extends ServiceSupport implements TransactionStrategy { |
32 |
|
private EntityManagerFactory entityManagerFactory; |
33 |
|
private EntityManager entityManager; |
34 |
|
|
35 |
0 |
public DefaultTransactionStrategy(EntityManagerFactory entityManagerFactory) { |
36 |
0 |
notNull(entityManagerFactory, "entityManagerFactory"); |
37 |
0 |
this.entityManagerFactory = entityManagerFactory; |
38 |
0 |
} |
39 |
|
|
40 |
0 |
public DefaultTransactionStrategy(EntityManager entityManager) { |
41 |
0 |
notNull(entityManager, "entityManager"); |
42 |
0 |
this.entityManager = entityManager; |
43 |
0 |
} |
44 |
|
|
45 |
|
public Object execute(JpaCallback callback) { |
46 |
0 |
EntityManager em = getEntityManager(); |
47 |
0 |
EntityTransaction transaction = em.getTransaction(); |
48 |
0 |
transaction.begin(); |
49 |
|
|
50 |
|
try { |
51 |
0 |
Object answer = callback.doInJpa(em); |
52 |
0 |
transaction.commit(); |
53 |
0 |
return answer; |
54 |
|
} |
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 |
|
} |