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

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 dbList = query.getResultList();
List resultList = new ArrayList();
if (dbList!=null && dbList.size()>0){
     for (int i =0;i 
 

@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 extends BaseDaoJpa
{
    protected MyBaseDao()
    {    }
 
  //unitName与LocalContainerEntityManagerFactoryBean类的容器对象的名称一致
    @PersistenceContext(unitName = "entityManagerFactory")
    public void setJpaEntityManager(EntityManager entityManager)
    {
        super.setEntityManager(entityManager);
    } 
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

你可能感兴趣的:(JPA之EntityManager踩坑及解决:更改PersistenceContext)