解决mybatis-plus3.X版本oracle的自增长ID自定义SqlSessionFactory不生效的问题

1:问题描述

采用自定义SqlSessionFactory后,采用官方文档配置方法,连接ORACLE数据库无法实现id自增长,经过调试会报以下错误,

2022-09-27 15:07:31.681 ERROR 9644 --- [nio-8285-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.type.TypeException: Could not set parameters for mapping: ParameterMapping{property='id', mode=IN, javaType=class java.lang.Long, jdbcType=null, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}. Cause: org.apache.ibatis.type.TypeException: Error setting null for parameter #1 with JdbcType OTHER . Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. Cause: java.sql.SQLException: 无效的列类型: 1111] with root cause

经过分析,主要是插入数据时,没有生成id导致传递了null,报错 

2:解决办法:在mybatis-plus3.4.*版本成功解决。以下为关键步骤

 代码:

@Bean
    public SqlSessionFactory sqlSessionFactoryBean1(@Qualifier("db1") DataSource dataSource, MybatisPlusInterceptor mybatisPlusInterceptor, GlobalConfig globalConfig) throws Exception {
        // 解决 Invalid bound statement 问题,必须使用 MybatisSqlSessionFactoryBean
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();

        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/db1/*.xml"));

        //注意这里,需要引入拦截器才能使分页生效
        factoryBean.setPlugins(mybatisPlusInterceptor);

        //注意这里,需要让oracle的sec生效,需要增加这部分代码
        factoryBean.setGlobalConfig(globalConfig);

        return factoryBean.getObject();
    }

    @Bean
    public OracleKeyGenerator oracleKeyGenerator(){
        log.info("==============oracleKeyGenerator");
        return new OracleKeyGenerator();
    }

    @Bean
    public GlobalConfig globalConfig() {
        GlobalConfig conf = new GlobalConfig();
        ArrayList<IKeyGenerator> iKeyGenerators = new ArrayList<>();
        iKeyGenerators.add(new OracleKeyGenerator());
        conf.setDbConfig(new GlobalConfig.DbConfig().setKeyGenerators(iKeyGenerators));
        return conf;
    }

实体类上增加:

oracle数据库创建自增长ID的sequence:

请自行创建oracle表,其中的表字段id,请使用number类型

-- 创建序列
create sequence seq_auto_increment_id
minvalue 1
maxvalue 999999999999
start with 1
increment by 1
nocache;

 经过以上处理后,在mybatis-plus3.4.x版本下,能成功插入数据并实现自增长

 


版权声明:本文为m0_59061013原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。