Spring 启动 Jpa 批处理 - CannotCreateTransactionException

Spring Boot Jpa Batch - CannotCreateTransactionException

我有一个 Spring Boot + JPA + Spring 批处理(+Spring 集成)项目。还有 Flyway,分开配置。 我已将 spring 批处理配置为使用与默认 "spring.jpa.datasource" 不同的数据源。这可以。 在我的 tasklet 中,我查询两个数据源,第一个 ds1 查询正确,第二个 ds2 查询出错:

org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.IllegalStateException: Already value [org.springframework.jdbc.datasource.ConnectionHolder@2fb082ff] for key [HikariDataSource (HikariPool-1)] bound to thread [main]

更多详情: 我为每个数据源配置 class,并用

注释
@Configuration 
@EnableTransactionManagement
@EnableJpaRepositories

在每个配置中,为 DataSource、LocalContainerEntityManagerFactoryBean 和 JpaTransactionManager 定义了一个具有自定义名称的 bean。

每个数据源的服务定义为:

 @Service @Transactional(transactionManager=JpaApsConfiguration.APS_TRANSACTION_MANAGER, propagation = Propagation.REQUIRES_NEW)

并且实体管理器是使用正确的限定符自动装配的 (注意:通过 JpaRepository classes 进行的查询)

关于什么可能导致此行为的任何建议?谢谢

注:

编辑:

这里是错误的完整堆栈跟踪:

2018-05-08 12:12:24 信息 o.s.batch.core.job.SimpleStepHandler - 执行步骤:[STEP#PROCESS_SHIPMENTS] 2018-05-08 12:12:24 错误 o.s.batch.core.step.AbstractStep - 在作业 PROCESS_APS 中执行步骤 STEP#PROCESS_SHIPMENTS 时遇到错误 org.springframework.transaction.CannotCreateTransactionException: 无法为事务打开 JPA EntityManager;嵌套异常是 java.lang.IllegalStateException:已将键 [HikariDataSource (HikariPool-1)] 的值 [org.springframework.jdbc.datasource.ConnectionHolder@351e89fc] 绑定到线程 [main] 在 org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:450) 在 org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:378) 在 org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:474) 在 org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:289) 在 org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) 在 org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) 在 org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689) 在 dkr.astreconnector.service.GespeService$$EnhancerBySpringCGLIB$$73dbb368.getValueDetailByUniq() 在 dkr.astreconnector.batch.worker.ShipmentProcessor.process(ShipmentProcessor.java:63) 在 dkr.astreconnector.batch.worker.ShipmentProcessor.process(ShipmentProcessor.java:30) 在 org.springframework.batch.core.step.item.SimpleChunkProcessor.doProcess(SimpleChunkProcessor.java:126) 在 org.springframework.batch.core.step.item.SimpleChunkProcessor.transform(SimpleChunkProcessor.java:303) 在 org.springframework.batch.core.step.item.SimpleChunkProcessor.process(SimpleChunkProcessor.java:202) 在 org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:75) 在 org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:406) 在 org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:330) 在 org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140) 在 org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:272) 在 org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:81) 在 org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:375) 在 org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) 在 org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:145) 在 org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:257) 在 org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:200) 在 org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148) 在 org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:66) 在 org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:67) 在 org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:169) 在 org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:144) 在 org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:136) 在 org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:308) 在 org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:141) 在 org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) 在 org.springframework.batch.core.launch.support.SimpleJobLauncher.运行(SimpleJobLauncher.java:134) 在 org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.execute(JobLauncherCommandLineRunner.java:163) 在 org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.executeLocalJobs(JobLauncherCommandLineRunner.java:179) 在 org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.launchJobFromProperties(JobLauncherCommandLineRunner.java:134) 在 org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.run(JobLauncherCommandLineRunner.java:128) 在 org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:790) 在 org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:774) 在 org.springframework.boot.SpringApplication.run(SpringApplication.java:335) 在 org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) 在 org.springframework.boot.SpringApplication.run(SpringApplication.java:1234) 在 dkr.astreconnector.AstreConnectorBatchApplication.main(AstreConnectorBatchApplication.java:14) Caused by: java.lang.IllegalStateException: 已将键 [HikariDataSource (HikariPool-1)] 的值 [org.springframework.jdbc.datasource.ConnectionHolder@351e89fc] 绑定到线程 [main] 在 org.springframework.transaction.support.TransactionSynchronizationManager.bindResource(TransactionSynchronizationManager.java:193) 在 org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:425) ...省略了 43 个常见框架 2018-05-08 12:12:24 INFO o.s.b.c.l.support.SimpleJobLauncher - 作业:[FlowJob: [name=PROCESS_APS]] 使用以下参数完成:[{run.id=128}] 和以下状态:[失败]

有点晚了,不过我想回复@mad_fox

主数据库:

@Configuration
@EnableJpaRepositories(
    entityManagerFactoryRef = JpaAppsConfiguration.APPS_ENTITY_MANAGER,
    transactionManagerRef = "transactionManager",
    basePackages = { JpaAppsConfiguration.APPS_REPOSITORIES })
@EnableAutoConfiguration
public class JpaAppsConfiguration {

public final static String APPS_PERSISTENCE_UNIT = "apps";
public final static String APPS_DATA_SOURCE = "appDs";
public final static String APPS_ENTITY_MANAGER = "appsEmf";
public final static String APPS_TRANSACTION_MANAGER = "appsTm";
protected final static String APPS_PACKAGES = ""; //my models package
protected final static String APPS_REPOSITORIES = ""; //my repos package

@Primary
@Bean(name = APPS_DATA_SOURCE)
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource appsDataSource() {
    return DataSourceBuilder.create().build();
}

@Primary
@Bean(name = APPS_ENTITY_MANAGER)
@PersistenceContext(unitName = APPS_PERSISTENCE_UNIT)
public LocalContainerEntityManagerFactoryBean appsEntityManagerFactory(EntityManagerFactoryBuilder builder,
        @Qualifier(APPS_DATA_SOURCE) DataSource appsDataSource) {
    LocalContainerEntityManagerFactoryBean emf = builder
            .dataSource(appsDataSource)
            .persistenceUnit(APPS_PERSISTENCE_UNIT)
            .packages(APPS_PACKAGES)
            .build();

    // Vendor adapter
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    emf.setJpaVendorAdapter(vendorAdapter);
    return emf;
}
}

二级数据库:

@Configuration
@EnableJpaRepositories(
    entityManagerFactoryRef = JpaGepeConfiguration.GEPE_ENTITY_MANAGER, 
    basePackages = { JpaGepeConfiguration.GEPE_REPOSITORIES })
@EnableAutoConfiguration
public class JpaGepeConfiguration {

public static final String GEPE_PERSISTENCE_UNIT = "gn1";
public static final String GEPE_DATA_SOURCE = "gn1ds";
public static final String GEPE_ENTITY_MANAGER = "gn1emf";
public static final String GEPE_TRANSACTION_MANAGER = "gn1tm";
public static final String GEPE_PACKAGES = ""; //my models package
public static final String GEPE_REPOSITORIES = ""; //my repos package

@Bean(name = GEPE_DATA_SOURCE)
@ConfigurationProperties(prefix = "gn1.datasource")
public DataSource gepeDataSource() {
    return DataSourceBuilder.create().build();
}

@Bean(name = GEPE_ENTITY_MANAGER)
@PersistenceContext(unitName = GEPE_PERSISTENCE_UNIT)
public LocalContainerEntityManagerFactoryBean gepeEntityManagerFactory(EntityManagerFactoryBuilder builder,
        @Qualifier(GEPE_DATA_SOURCE) DataSource gepeDataSource) {
    LocalContainerEntityManagerFactoryBean emf = builder
            .dataSource(gepeDataSource)
            .persistenceUnit(GEPE_PERSISTENCE_UNIT)
            .packages(GEPE_PACKAGES)
            .build();

    // Vendor adapter
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    emf.setJpaVendorAdapter(vendorAdapter);
    return emf;
}
}

主数据库的@Service 类 中的方法注释为:

@Transactional(transactionManager = JpaAppsConfiguration.APPS_TRANSACTION_MANAGER, readOnly = false, propagation = Propagation.REQUIRED, noRollbackFor = Exception.class)

属性文件中的参数如下:

#DATABASE CONNECTION
#Primary
spring.datasource.username=
spring.datasource.password=
spring.datasource.driverClassName=
spring.datasource.url=j
spring.datasource.jdbcUrl=
spring.datasource.name=
#Secondary
gepe.datasource.username=
gepe.datasource.password=
gepe.datasource.driverClassName=
gepe.datasource.url=
gepe.datasource.jdbcUrl=
gepe.datasource.name=

希望这对您有所帮助。

这里是批量配置的代码片段。确保您还覆盖了 getTransactionManager 方法。 (用你的替换 qualifires 的值)

@Configuration
public class CustomBatchConfigurer extends DefaultBatchConfigurer {
    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource dataSource;

    @Autowired
    @Qualifier("primaryTransactionManager")
    private PlatformTransactionManager transactionManager;

    @Override
    public PlatformTransactionManager getTransactionManager() {
        return transactionManager;
    }

    @Override
    protected JobRepository createJobRepository() throws Exception {
        JobRepositoryFactoryBean factoryBean = new JobRepositoryFactoryBean();
        factoryBean.setIsolationLevelForCreate("ISOLATION_REPEATABLE_READ");
        factoryBean.setDataSource(dataSource);
        factoryBean.setTransactionManager(transactionManager);

        factoryBean.afterPropertiesSet();
        return factoryBean.getObject();
    }
}