1 | |
package org.kuali.student.common.util.spring; |
2 | |
|
3 | |
import java.lang.reflect.Field; |
4 | |
import java.util.Map; |
5 | |
|
6 | |
import javax.persistence.spi.PersistenceUnitTransactionType; |
7 | |
|
8 | |
import org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager; |
9 | |
import org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo; |
10 | |
|
11 | 0 | public class MergingPersistenceUnitManager extends |
12 | |
DefaultPersistenceUnitManager { |
13 | |
|
14 | |
private String mergedPersistenceUnitName; |
15 | 0 | private PersistenceUnitTransactionType transactionTypeOverride = PersistenceUnitTransactionType.RESOURCE_LOCAL; |
16 | |
|
17 | |
public void setMergedPersistenceUnitName(String mergedPersistenceUnitName) { |
18 | 0 | this.mergedPersistenceUnitName = mergedPersistenceUnitName; |
19 | 0 | } |
20 | |
|
21 | |
@Override |
22 | |
protected void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) { |
23 | |
try { |
24 | 0 | Field persistenceUnitInfosField = DefaultPersistenceUnitManager.class.getDeclaredField("persistenceUnitInfos"); |
25 | 0 | persistenceUnitInfosField.setAccessible(true); |
26 | 0 | Map<String, MutablePersistenceUnitInfo> persistenceUnitInfos = (Map<String, MutablePersistenceUnitInfo>) persistenceUnitInfosField.get(this); |
27 | |
|
28 | 0 | if(persistenceUnitInfos.isEmpty()){ |
29 | 0 | pui.setPersistenceUnitName(mergedPersistenceUnitName); |
30 | 0 | pui.setTransactionType(transactionTypeOverride); |
31 | |
}else{ |
32 | 0 | MutablePersistenceUnitInfo currentlyMergedPui = persistenceUnitInfos.get(mergedPersistenceUnitName); |
33 | 0 | for(String className:pui.getManagedClassNames()){ |
34 | 0 | currentlyMergedPui.getManagedClassNames().add(className); |
35 | |
} |
36 | |
} |
37 | |
|
38 | 0 | } catch (Exception e) { |
39 | 0 | throw new RuntimeException("Error while merging persistence units.",e); |
40 | 0 | } |
41 | |
|
42 | 0 | super.postProcessPersistenceUnitInfo(pui); |
43 | 0 | } |
44 | |
|
45 | |
public void setTransactionTypeOverride(PersistenceUnitTransactionType transactionTypeOverride) { |
46 | 0 | this.transactionTypeOverride = transactionTypeOverride; |
47 | 0 | } |
48 | |
|
49 | |
|
50 | |
} |