1.创建序列并绑定id
CREATE SEQUENCE biz_factory_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
"id" int4 NOT NULL DEFAULT nextval('sys_user_seq'::regclass),
2.实体设置KeySequence和TableId注解
注意IdType.INPUT 和 @KeySequence(value = "biz_factory_seq", dbType = DbType.POSTGRE_SQL)
3.GlobalConfig 配置 PostgreKeyGenerator
@EnableTransactionManagement
public class DataSourceConfig {...@Bean(name = "pgKeyGenerator")public PostgreKeyGenerator postgreKeyGenerator() {return new PostgreKeyGenerator();}@Bean(name = "dbConfig")public GlobalConfig.DbConfig dbConfig() {GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();dbConfig.setKeyGenerator(postgreKeyGenerator());return dbConfig;}@Bean(name = "globalConfig")public GlobalConfig globalConfig() {GlobalConfig globalConfig = new GlobalConfig();globalConfig.setDbConfig(dbConfig());return globalConfig;}}
4. 到这里应该就配置完成,可以正常新增并且使用序列自增id,但我的项目还是在报错:
### Error updating database. Cause: org.postgresql.util.PSQLException: ERROR: null value in column \"id\" of relation \"biz_factory\" violates not-null
- 一直报错id为空,没有去获取序列的值,未配置成功
- 然后就一直找问题,试了很多办法,依然没有解决
- 后来我全局查看,我的项目用的多数据源,数据源单独配置了SqlSessionFactory,考虑是不是postgreKeyGenerator没有配置进去
5.解决
//添加mybatis-plus 对pg自用序列的主键自增配置
GlobalConfig conf = new GlobalConfig();
conf.setDbConfig(new GlobalConfig.DbConfig().setKeyGenerators(Arrays.asList(new PostgreKeyGenerator())));
factoryBean.setGlobalConfig(conf);
- 将配置添加进SqlSessionFactory,然后就成功了
- 先去查序列的值,再执行插入
6.总结
- 这个问题,耗了一下午,一定要坚持不放弃
- 全局审视非常重要