View Javadoc

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  public class MergingPersistenceUnitManager extends
12  		DefaultPersistenceUnitManager {
13  
14  	private String mergedPersistenceUnitName;
15  	private PersistenceUnitTransactionType transactionTypeOverride = PersistenceUnitTransactionType.RESOURCE_LOCAL;
16  	
17  	public void setMergedPersistenceUnitName(String mergedPersistenceUnitName) {
18  		this.mergedPersistenceUnitName = mergedPersistenceUnitName;
19  	}
20  
21  	@Override
22  	protected void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) {
23  		try {
24  			Field persistenceUnitInfosField = DefaultPersistenceUnitManager.class.getDeclaredField("persistenceUnitInfos");
25  			persistenceUnitInfosField.setAccessible(true);
26  			Map<String, MutablePersistenceUnitInfo> persistenceUnitInfos = (Map<String, MutablePersistenceUnitInfo>) persistenceUnitInfosField.get(this);
27  
28  			if(persistenceUnitInfos.isEmpty()){
29  				pui.setPersistenceUnitName(mergedPersistenceUnitName);
30  				pui.setTransactionType(transactionTypeOverride);
31  			}else{
32  				MutablePersistenceUnitInfo currentlyMergedPui = persistenceUnitInfos.get(mergedPersistenceUnitName);
33  				for(String className:pui.getManagedClassNames()){
34  					currentlyMergedPui.getManagedClassNames().add(className);
35  				}
36  			}
37  			
38  		} catch (Exception e) {
39  			throw new RuntimeException("Error while merging persistence units.",e);
40  		}
41  		
42  		super.postProcessPersistenceUnitInfo(pui);
43  	}
44  
45  	public void setTransactionTypeOverride(PersistenceUnitTransactionType transactionTypeOverride) {
46  		this.transactionTypeOverride = transactionTypeOverride;
47  	}
48  
49  
50  }