首頁 > 軟體

JPA之EntityManager踩坑及解決:更改PersistenceContext

2022-02-24 13:01:28

JPA EntityManager踩坑之更改PersistenceContext

一、原因

專案中設定兩個Spring JPA的資料來源,使用EntityManager的時候預設是選擇第一個,導致查詢不到第二個資料來源的資料。

二、Spring JPA多資料來源怎麼使用EntityManager

1. Spring JPA多資料來源的設定請檢視此文章:SpringData JPA基本/高階/多資料來源使用

2. 引入EntityManager:

@PersistenceContext(unitName = "primaryPersistenceUnit")
private EntityManager entityManager;

@PersistenceContext中的unitName指的是使用哪一個資料來源的persistenceUnit,persistenceUnit是在設定資料來源的時候設定的,每一個資料來源的persistenceUnit都是不一樣的,這樣就可以使用不同的資料來源來查詢資料了。

設定persistenceUnit:

@Bean(name = "entityManagerFactoryPrimary")
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
    return builder
            .dataSource(primaryDataSource)
            .properties(vendorProperties)
            .packages("com.neo.model") //設定實體類所在位置
            .persistenceUnit("primaryPersistenceUnit")
            .build();
}

三、使用EntityManager

String SQL = "select id ,code,name,'desc' from drgo_cd10_dx_code where name like ('%"+content.trim()+"%') " 
logger.info("search getProductOwnerId SQL:"+SQL);
Query query = entityManager.createNativeQuery(SQL);
List<Object[]> dbList = query.getResultList();
List<ICD10CodeData> resultList = new ArrayList<ICD10CodeData>();
if (dbList!=null && dbList.size()>0){
     for (int i =0;i<dbList.size();i++){
      Object[] o = dbList.get(i);
      String id = o[0]==null?"":o[0].toString();
      String code = o[1]==null?"":o[1].toString();
      String name = o[0]==null?"":o[2].toString();
      String desc = o[1]==null?"":o[3].toString();
      ICD10CodeData tempCode = new ICD10CodeData(Long.parseLong(id), code, name, desc);
      resultList.add(tempCode);
     }
 }

@PersistenceContext(unitName = "entityManagerFactory")

@Configuration
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ, proxyTargetClass = true)
@ComponentScan({cn.com.appName.manager,cn.com.appName.dao,cn.com.appName.dao.jpa}) 
public class AppConfig extends AbstractManager
{
     @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean()
    {
        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
        factoryBean.setDataSource(dataSource(null));
        factoryBean.setPackagesToScan(new String[] { "cn.com." + AppConfig.APP_NAME + ".entity" });
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setDatabasePlatform(hibernateDialect);
        if (logger.isDebugEnabled())
        {
            // vendorAdapter.setShowSql(true);
            // vendorAdapter.setGenerateDdl(true);
        }
        //vendorAdapter.setGenerateDdl(true);
        factoryBean.setJpaVendorAdapter(vendorAdapter);
        // factoryBean.setJpaProperties(this.additionlProperties());
        return factoryBean;
    } 
} 
public abstract class MyBaseDao<E extends BaseEntity> extends BaseDaoJpa<E>
{
    protected MyBaseDao()
    {    }
 
  //unitName與LocalContainerEntityManagerFactoryBean類的容器物件的名稱一致
    @PersistenceContext(unitName = "entityManagerFactory")
    public void setJpaEntityManager(EntityManager entityManager)
    {
        super.setEntityManager(entityManager);
    } 
}

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com