mybatis-plus 实现自增id且可手动输入id的方式
在用mybatisplus的时候可以通过注解实体字段从而实现对象和数据库字段的映射,其中主键id基本上采用的是mysql数据库自增的方式,如果此时采用
@TableId(value = "id", type = IdType.AUTO)方式,则每次插入一条数据都将只会用到数据库的自增id并把id返回注入到实体对象,此时如果想要手动插入id(基本上在同步数据的时候用到),就无法实现
如果此时采用
@TableId(value = "id", type = IdType.INPUT)方式,在对象id为空的时候确实也能实现自增,在id不为空的时候也能插入想要的id,不过无法获得插入成功返回的id,此时如果也想获得返回的id,只需要重写mybatisplus的预处理器即可,总共3个步骤,如下:
1、添加一个继承mybatisplus 抽象注入方法的类,在这个类里面重写自定义 MappedStatement方法,在方法里面对主键进行自增generate声明处理便于mybatisplus把数据插入成功的id封装到实体对象中
@SuppressWarnings("all")
public class Insert extends AbstractMethod {@Overridepublic MappedStatement injectMappedStatement(Class> mapperClass, Class> modelClass, TableInfo tableInfo) {KeyGenerator keyGenerator = new NoKeyGenerator();SqlMethod sqlMethod = SqlMethod.INSERT_ONE;String columnScript = SqlScriptUtils.convertTrim(tableInfo.getAllInsertSqlColumnMaybeIf(null),LEFT_BRACKET, RIGHT_BRACKET, null, COMMA);String valuesScript = SqlScriptUtils.convertTrim(tableInfo.getAllInsertSqlPropertyMaybeIf(null),LEFT_BRACKET, RIGHT_BRACKET, null, COMMA);String keyProperty = null;String keyColumn = null;// 表包含主键处理逻辑,如果不包含主键当普通字段处理if (StringUtils.isNotBlank(tableInfo.getKeyProperty())) {keyGenerator = new Jdbc3KeyGenerator();keyProperty = tableInfo.getKeyProperty();keyColumn = tableInfo.getKeyColumn();}String sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), columnScript, valuesScript);SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);return this.addInsertMappedStatement(mapperClass, modelClass, getMethod(sqlMethod), sqlSource, keyGenerator, keyProperty, keyColumn);}
}
2、创建一个继承默认mybatis-plus的默认注入器,并把上面的自定义的注入mappedstatement方法添加进去
public class MySqlInjector extends DefaultSqlInjector {@Overridepublic List getMethodList(Class> mapperClass) {List methodList = super.getMethodList(mapperClass);methodList.removeIf(e -> e instanceof Insert);methodList.add(new com.test.method.Insert());return methodList;}
}
3、实体对象采用input方式即可
@TableId(value = "id", type = IdType.INPUT)private Long id;
4、将MySqlInjector注入到DataSource数据源中
@EnableTransactionManagement
@Configuration
@MapperScan("com.test.*.*.mapper")
public class MyBatisConfig {@Resourceprivate DataSource myRoutingDataSource;@Autowiredprivate MybatisPlusInterceptor mybatisPlusInterceptor;@Value("${mybatis-plus.mapper-locations}")private String mapperLocations;@Beanpublic SqlSessionFactory sqlSessionFactory() throws Exception {MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();sqlSessionFactoryBean.setPlugins(new Interceptor[]{mybatisPlusInterceptor});sqlSessionFactoryBean.setDataSource(myRoutingDataSource);GlobalConfig globalConfig=new GlobalConfig();globalConfig.setSqlInjector(new MySqlInjector());sqlSessionFactoryBean.setGlobalConfig(globalConfig);PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();sqlSessionFactoryBean.setMapperLocations(resolver.getResources(mapperLocations));// SpringBoot项目集成mybatis打包为jar运行时setTypeAliasesPackage无效解决VFS.addImplClass(SpringBootVFS.class);return sqlSessionFactoryBean.getObject();}@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {//分表拦截器MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}
5、yml配置加入mybatis-plus的配置
mybatis-plus:# 配置mapper的扫描,找到所有的mapper.xml映射文件mapper-locations: classpath:mybatis/mapper/**/*Mapper.xmlglobal-config:# 主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";id-type: 0
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
