SpringBatch适配不同数据库的两种方法

一、配置JobRepository

@Configuration
@EnableBatchProcessing
public class TaskArrangeConfig extends DefaultBatchConfigurer {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private JobExplorer jobExplorer;

    @Autowired
    private JobRegistry jobRegistry;

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    MapperConfig MapperConfig;


    @Bean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }


    @Override
    protected JobRepository createJobRepository() throws Exception {
        JobRepositoryFactoryBean factoryBean = new JobRepositoryFactoryBean();
        if(MapperConfig.getDbType().equals(JDialectConsts.ORACLE) || MapperConfig.getDbType().equals(JDialectConsts.DAMENG)){
            factoryBean.setDatabaseType(DatabaseType.ORACLE.name());
        }else if(MapperConfig.getDbType().equals(JDialectConsts.MYSQL)){
            factoryBean.setDatabaseType(DatabaseType.MYSQL.name());
        }else {
            factoryBean.setDatabaseType(DatabaseType.H2.name());
        }
        factoryBean.setDataSource(dataSource);
        factoryBean.setTransactionManager(transactionManager());
        return factoryBean.getObject();
    }

    @Bean
    public JobOperator jobOperator(){
        SimpleJobOperator simpleJobOperator=new SimpleJobOperator();
        simpleJobOperator.setJobLauncher(jobLauncher);
        simpleJobOperator.setJobParametersConverter(new DefaultJobParametersConverter());
        simpleJobOperator.setJobRegistry(jobRegistry);
        simpleJobOperator.setJobExplorer(jobExplorer);
        simpleJobOperator.setJobRepository(jobRepository);
        return simpleJobOperator;
    }

}

二、覆盖batch下support包中的类 (以达梦数据库为例)

修改 DefaultDataFieldMaxValueIncrementerFactory

getIncrementer 中添加DbType SpringBatch适配不同数据库的两种方法_第1张图片
DatabaseType 类添加数据库

public enum DatabaseType {

    DERBY("Apache Derby"),
    DB2("DB2"),
    DB2VSE("DB2VSE"),
    DB2ZOS("DB2ZOS"),
    DB2AS400("DB2AS400"),
    HSQL("HSQL Database Engine"),
    SQLSERVER("Microsoft SQL Server"),
    MYSQL("MySQL"),
    ORACLE("Oracle"),
    POSTGRES("PostgreSQL"),
    SYBASE("Sybase"),
    H2("H2"),
    SQLITE("SQLite"),
    DM("DM DBMS");

DatabaseDriver 添加达梦驱动信息

  DM("DM DBMS","dm.jdbc.driver.DmDriver","dm.jdbc.driver.DmdbXADataSource","SELECT 'Hello' from DUAL"){
        @Override
        public String getId() {
            return "oracle";
        }
    }

注意: 方法二需要创建同名类且包名相同放在SpringBoot启动类所在的同级目录

你可能感兴趣的:(数据库,SpringBatch)