Mybatis中通用Mapper的InsertList()用法,
分享于 点击 31497 次 点评:157
Mybatis中通用Mapper的InsertList()用法,
目录
- 关于通用mapper中的的insertList()方法
- tk.mybatis.mapper.common.special.InsertListMapper包下的insertList()方法
- tk.mybatis.mapper.additional.insert.InsertListMapper包下的insertList()方法
- 总结
关于通用mapper中的的insertList()方法
针对通用Mapper中批量新增时是否需要自增ID或者自定义ID时需要使用不同包下的insertList()
通常批量插入的ID非自增的ID(及自定义生成ID策略),所以tk.mybatis.mapper.additional.insert.InsertListMapper包下的insertList()经常用在项目组中
配合@Intercepts 自定义 Mybatis 拦截 update 操作(添加和修改)
tk.mybatis.mapper.common.special.InsertListMapper包下的insertList()方法
- pom导入:
<dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-base</artifactId> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-core</artifactId> </dependency>
使用该方法的实体类主键必须是自增的(需要在实体类中指出)。
如果实体的主键名为’id’,同时主键自增。在不修改代码的情况下,使用insertList()方法实现的批量插入数据后通用mapper能自动回写主键值到实体对象中。
- 如以下实体类和对应mapper:
@Data @Table(name = "user") public class User { @Id @KeySql(useGeneratedKeys = true) private Integer id; private String username; private String desc; } public interface UserMapper extends InsertListMapper<User> { }
如果实体类主键名不是id,同时实体类主键是自增的,想要实现实体类主键回写,需要重写insertList()方法,其实就是修改了注解上的值,把@Options注解上的keyProperty值改为自己实体类的主键名
- 如以下实体类和对应的mapper:
@Data @Table(name = "user") public class User { @Id @KeySql(useGeneratedKeys = true) private Integer uid; private String username; private String desc; } public interface UserMapper extends Mapper<User>, InsertListMapper<User> { @Options(keyProperty = "uid",useGeneratedKeys = true) @InsertProvider(type = SpecialProvider.class, method = "dynamicSQL") int insertList(List<User> recordList); }
tk.mybatis.mapper.additional.insert.InsertListMapper包下的insertList()方法
- pom导入:
<!-- https://mvnrepository.com/artifact/tk.mybatis/mapper-extra --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-extra</artifactId> <version>1.1.5</version> </dependency>
- 该方法不支持主键策略,需要在实体类中指定主键。
- 该方法执行后不会回写实体类的主键值。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持3672js教程。
您可能感兴趣的文章:- MyBatis Mapper.xml入参List使用in函数问题
- Mybatis mapper.xml使用全局变量的三种实现方法
- MyBatis中 @Mapper 和 @MapperScan 的区别与使用解析
- MyBatis Mapper.XML 标签使用小结
- mybatis-config.xml文件中的mappers标签使用
- mybatis使用mapper代理开发方式
- MyBatis实战之Mapper注解的示例
用户点评