001    package org.kuali.student.common.util.spring;
002    
003    import java.lang.reflect.Field;
004    import java.util.Map;
005    
006    import javax.persistence.spi.PersistenceUnitTransactionType;
007    
008    import org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager;
009    import org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo;
010    
011    public class MergingPersistenceUnitManager extends
012                    DefaultPersistenceUnitManager {
013    
014            private String mergedPersistenceUnitName;
015            private PersistenceUnitTransactionType transactionTypeOverride = PersistenceUnitTransactionType.RESOURCE_LOCAL;
016            
017            public void setMergedPersistenceUnitName(String mergedPersistenceUnitName) {
018                    this.mergedPersistenceUnitName = mergedPersistenceUnitName;
019            }
020    
021            @Override
022            protected void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) {
023                    try {
024                            Field persistenceUnitInfosField = DefaultPersistenceUnitManager.class.getDeclaredField("persistenceUnitInfos");
025                            persistenceUnitInfosField.setAccessible(true);
026                            Map<String, MutablePersistenceUnitInfo> persistenceUnitInfos = (Map<String, MutablePersistenceUnitInfo>) persistenceUnitInfosField.get(this);
027    
028                            if(persistenceUnitInfos.isEmpty()){
029                                    pui.setPersistenceUnitName(mergedPersistenceUnitName);
030                                    pui.setTransactionType(transactionTypeOverride);
031                            }else{
032                                    MutablePersistenceUnitInfo currentlyMergedPui = persistenceUnitInfos.get(mergedPersistenceUnitName);
033                                    for(String className:pui.getManagedClassNames()){
034                                            currentlyMergedPui.getManagedClassNames().add(className);
035                                    }
036                            }
037                            
038                    } catch (Exception e) {
039                            throw new RuntimeException("Error while merging persistence units.",e);
040                    }
041                    
042                    super.postProcessPersistenceUnitInfo(pui);
043            }
044    
045            public void setTransactionTypeOverride(PersistenceUnitTransactionType transactionTypeOverride) {
046                    this.transactionTypeOverride = transactionTypeOverride;
047            }
048    
049    
050    }