Mybatis-plus 使用
最佳答案 问答题库348位专家为你答疑解惑
1. 注解使用
mybatis-plus提供了 ·@TableName·, @TableId, @TableField, @TableLogic 四种注解,其含义分别为:
@TableName
@TableName("SPF_Require_Vehicle") 用于声明当前class所对应数据库中的表,如果class的名字和表的名字完全相同,则不需要添加该注解,如果不一样,则需要用该注解进行声明。
@TableId
@TableId(value = "SPF_UID", type = IdType.AUTO) 用于声明主键, value指定数据库中主键的名称,type为主键的生成类型,支持 Assign(雪花算法,java字段需要是Long)、Auto(数据库字段需要声明为auto_increment), uuid
@TableField
@TableField("SPF_Name") 用于声明当前字段对应的表中的字段
@TableLogic
@TableLogic(value = "0", delval = "1") 用于软删除,value是默认值,delval表示软删除后的值。
@TableName("SPF_Require_Vehicle")
@Data
public class Employee {/*** 指定主键名称为SPF_uid, 类型为自增,即数据库的字段必须是auto_increment*/@TableId(value = "SPF_UID", type = IdType.AUTO)private Long id;/*** 指定数据库中对应的字段是 Part_PartSap*/@TableField("Part_PartSap")private String partSap;@TableField("Part_PlateSap")private String plateSap;@TableField("SPF_Name")private String name;/*** 逻辑删除*/@TableLogic(value = "0", delval = "1")@TableField("IsActvie")private Boolean active;
}
@EnumValue
代码简洁性考虑:许多时候需要用到Enum,例如0表示男1表示女、0表示关闭1表示打开,and so on
- 在数据库表中增加字段gender: 0表示男,1表示女
- 定义枚举类, @EnumValue注解表示该字段是向数据库中插入的值,@JsonValue表示读取的时候对外展示的值
@Getter
public enum SexEnum {SEX_MALE(0, "男"),SEX_FEMALE(1, "女");/*** 表示当前字段是执行insert时向数据库中插入的字段*/@EnumValueprivate int sexVal;/*** 表示从数据库读取的时候对外显示的值*/@JsonValueprivate String sexName;SexEnum(int sexVal, String sexName) {this.sexVal = sexVal;this.sexName = sexName;}/*** 配合 @JsonValue使用* @return 返回展示的值*/@Overridepublic String toString() {return this.sexName;}
}
3. 使用处
插入的值为枚举注释的值
读取的是 @JsonValue注释的值
2. IService使用
2.1 批量插入
boolean saveBatch(Collection<T> entityList, int batchSize);
@Testpublic void baseBatchInsertTest() {List<Employee> list = new ArrayList<>();for (int i = 20; i < 30; i++) {Employee employee = new Employee();employee.setName("zhagnsan" + i);employee.setPartSap("123425-" + i);employee.setPlateSap("312342-" + i);list.add(employee);}// 批量插入,service提供了两个函数,可以带第二个参数,也可以不带,不带的情况下默认是1000// 批量插入实际也是一条一条的插入,不同的是底层启动了同一个session,插入完成后关闭,不需要每次都开启关闭this.service.saveBatch(list, 10);}
2.2 批量插入修改
如果主键Id已经在表中存在则修改,如果不存在则插入一条新数据
// 第二个参数选填,默认是1000
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);
@Testpublic void testBatchInsertOrUpdate() {List<Employee> list = new ArrayList<>();Employee e1 = new Employee();// 1L已经存在,会指定updatee1.setId(1L);// 只添加了一个字段,也就是只修改一个字段e1.setName("车轱辘");Employee e2 = new Employee();// id在表中不存在,则新增e2.setId(50L);e2.setName("车顶");e2.setPartSap("123142314-00");e2.setPlateSap("423414-09");list.add(e1);list.add(e2);this.service.saveOrUpdateBatch(list,2);}
2.2 单个插入修改
// 如果id存在则修改,否则插入
boolean saveOrUpdate(T entity);
2.3 单个删除
default boolean removeById(Serializable id)
default boolean removeById(T entity)
@Testpublic void testRemoveSingle01() {/*** id如果存在则删除,返回ture,否则返回false*/boolean b = this.service.removeById(9);System.out.println("b:" + b);}/*
* 有的时候,前端传过来的是一个类,此时可以直接调用该函数删除
*/
@Testpublic void testRemoveSignle02() {Employee employee = new Employee();employee.setId(8L);this.service.removeById(employee);}
2.4 有条件删除
实际中很多情况并不是根据Id进行删除而是根据实际需要进行删除, service也提供了该功能
removeByMap
default boolean removeByMap(Map<String, Object> columnMap)
/*
* 下面代码执行的语句如下
* UPDATE SPF_Require_Vehicle SET IsActvie=1 WHERE Part_PlateSap = ? AND Part_PartSap = ? AND IsActvie=0
*/
@Testpublic void testRemoveByMap() {Map<String, Object> map = new HashMap<>();map.put("Part_PartSap", "123425-0");map.put("Part_PlateSap", "312342-0");this.service.removeByMap(map);}
remove(可根据条件批量删除)
也可以根据wrapper进行删除,删除的时候使用的是QueryWrapper, Wrapper的用法有很多种,此处只展示in的用法,其他用法下文进行介绍
default boolean remove(Wrapper<T> queryWrapper)
@Testpublic void testRemove03() {QueryWrapper<Employee> wrapper = new QueryWrapper<>();List<Long> list = new ArrayList<>();list.add(2L);list.add(3L);list.add(4L);wrapper.in(list != null && !list.isEmpty(), "SPF_UID", list);/*** UPDATE SPF_Require_Vehicle SET IsActvie=1 WHERE IsActvie=0 AND (SPF_UID IN (?,?,?))*/this.service.remove(wrapper);}
2.5 批量删除
根据主键批量删除
removeByIds
default boolean removeByIds(Collection<?> list)
@Testpublic void testRemoveByIds() {List<Long> list = new ArrayList<>();list.add(2L);list.add(3L);list.add(5L);/*** 根据Ids批量删除* UPDATE SPF_Require_Vehicle SET IsActvie=1 WHERE SPF_UID IN ( ? , ? , ? ) AND IsActvie=0*/this.service.removeByIds(list);}
removeBatchByIds
采用jdbc批量删除,底层使用for循环逐个删除,这点是和上面函数的区别
default boolean removeBatchByIds(Collection<?> list, int batchSize)
@Testpublic void testremoveBatchByIds() {List<Long> list = new ArrayList<>();list.add(2L);list.add(3L);list.add(5L);/*** UPDATE SPF_Require_Vehicle SET IsActvie=1 WHERE SPF_UID=? AND IsActvie=0*/this.service.removeBatchByIds(list, list.size());}
2.6 单个修改:根据Id修改
default boolean updateById(T entity)
@Testpublic void testupdateById() {Employee employee = new Employee();employee.setId(8L);employee.setName("doris");/*** UPDATE SPF_Require_Vehicle SET SPF_Name=? WHERE SPF_UID=? AND IsActvie=0*/this.service.updateById(employee);}
2.7 有条件修改:根据wrapper修改
default boolean update(Wrapper<T> updateWrapper)
@Testpublic void testupdate() {Integer minId = 9;Integer maxId = 14;String name = "doris";String nName = "wangshun";LambdaUpdateWrapper<Employee> wrapper = new LambdaUpdateWrapper<>();wrapper.gt(minId != null, Employee::getId, minId).lt(maxId != null, Employee::getId, maxId).or().like(name != null && !name.isEmpty(), Employee::getName, name);wrapper.set(nName != null && !nName.isEmpty(), Employee::getName, nName);/*** UPDATE SPF_Require_Vehicle SET SPF_Name=? WHERE IsActvie=0 AND (SPF_UID > ? AND SPF_UID < ? OR SPF_Name LIKE ?)*/this.service.update(wrapper);}
2.8 批量修改:根据Id修改
这个方法很使用,实际工作中,都是根据前端传过来的结构体进行修改
boolean updateBatchById(Collection<T> entityList, int batchSize)
@Testpublic void testupdateBatchById() {List<Employee> list = new ArrayList<>();Employee e1 = new Employee();e1.setId(1L);e1.setName("wangwu");Employee e2 = new Employee();e2.setId(2L);e2.setName("wangbaochuan");list.add(e1);list.add(e2);/*** UPDATE SPF_Require_Vehicle SET SPF_Name=? WHERE SPF_UID=? AND IsActvie=0*/this.service.updateBatchById(list, list.size());}
2.9 单个查询
根据Id单个查询
getById
@Testpublic void testgetById() {/*** SELECT SPF_UID AS id,Part_PartSap AS partSap,Part_PlateSap AS plateSap,SPF_Name AS name,IsActvie AS active FROM SPF_Require_Vehicle WHERE SPF_UID=? AND IsActvie=0*/Employee byId = this.service.getById(1);System.out.println(byId);}
getOne
// 根据条件查找时:如果有多个则会抛出异常
default T getOne(Wrapper<T> queryWrapper)
@Testpublic void testgetOne() {LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();String plateSap = "312342-6";wrapper.eq(plateSap != null && !plateSap.isEmpty(), Employee::getPlateSap, plateSap);/*** SELECT SPF_UID AS id,Part_PartSap AS partSap,Part_PlateSap AS plateSap,SPF_Name AS name,IsActvie AS active* FROM SPF_Require_Vehicle WHERE IsActvie=0 AND (Part_PlateSap = ?)*/Employee one = this.service.getOne(wrapper);System.out.println(one);}
2.10 批量查询
listByIds
@Testpublic void testlistByIds() {List<Long> list = new ArrayList<>();list.add(1L);list.add(2L);list.add(3L);List<Employee> employees = this.service.listByIds(list);/*** SELECT SPF_UID AS id,Part_PartSap AS partSap,Part_PlateSap AS plateSap,SPF_Name AS name,IsActvie AS active FROM SPF_Require_Vehicle WHERE SPF_UID IN ( ? , ? , ? ) AND IsActvie=0*/employees.forEach(System.out::println);}
list
@Testpublic void testList() {List<Employee> list = this.service.list();/*** SELECT SPF_UID AS id,Part_PartSap AS partSap,Part_PlateSap AS plateSap,SPF_Name AS name,IsActvie AS active* FROM SPF_Require_Vehicle WHERE IsActvie=0*/list.forEach(System.out::println);}
2.11 有条件批量查询
listByMap
default List<T> listByMap(Map<String, Object> columnMap)
@Testpublic void testlistByMap() {Map<String, Object> map = new HashMap<>();map.put("SPF_Name", "wangshun");map.put("Part_PlateSap", "312342-20");/*** SELECT SPF_UID AS id,Part_PartSap AS partSap,Part_PlateSap AS plateSap,SPF_Name AS name,IsActvie AS active * FROM SPF_Require_Vehicle WHERE Part_PlateSap = ? AND SPF_Name = ? AND IsActvie=0*/List<Employee> employees = this.service.listByMap(map);employees.forEach(System.out::println);}
list
default List<T> list(Wrapper<T> queryWrapper)
@Testpublic void testList() {LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();wrapper.like(Employee::getName, "wangshun");List<Employee> list = this.service.list(wrapper);/*** SELECT SPF_UID AS id,Part_PartSap AS partSap,Part_PlateSap AS plateSap,SPF_Name AS name,IsActvie AS active * FROM SPF_Require_Vehicle WHERE IsActvie=0 AND (SPF_Name LIKE ?)*/list.forEach(System.out::println);}
2.12 查询指定列
getmap
// 如果查询出过个,则只取第一个
Map<String, Object> getMap(Wrapper<T> queryWrapper);
@Testpublic void testSelectMap() {String name = "wangshun";LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();wrapper.like(!name.isEmpty(), Employee::getName, name);/*** 只查询这两列,如果同时查询出多行,则只取第一行* SELECT Part_PlateSap AS plateSap,Part_PartSap AS partSap FROM SPF_Require_Vehicle WHERE IsActvie=0 AND (SPF_Name LIKE ?)*/wrapper.select(Employee::getPlateSap, Employee::getPartSap);Map<String, Object> map = this.service.getMap(wrapper);System.out.println(map);}
listMap
可查询多行
@Testpublic void testlistMaps() {LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();wrapper.like(Employee::getName, "wangshun");/*** 只显示这三列*/wrapper.select(Employee::getPartSap, Employee::getPlateSap, Employee::getName);List<Map<String, Object>> maps = this.service.listMaps(wrapper);for (Map<String, Object> map : maps) {System.out.println(map);}}
default List<Map<String, Object>> listMaps() 如果不见条件则查询所有的行
2.13 个数查询
// 查询表中国有效的总行数 default long count()
// 根据条件查询行数 default long count(Wrapper<T> queryWrapper)
2.14 分页查询
分页查询需要首先注册mybatis-plus的拦截器,配置如下
@Configuration
public class MpConfig {@Beanpublic MybatisPlusInterceptor getIntercepter() {MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return mybatisPlusInterceptor;}
}
@Testpublic void testPage01() {Page<Employee> page = new Page<>(2, 4);LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();wrapper.like(Employee::getName, "wangshun");this.service.page(page, wrapper);System.out.println(page);// 查询到的内容System.out.println("records: " + page.getRecords());// 总页数System.out.println("pages: " + page.getPages());// 当前页数System.out.println("current: " + page.getCurrent());// 总条目数System.out.println("total: " + page.getTotal());}
2.15 SQL分页查询
许多时候需要手写语句实现分页查询,例如同时从多张表中查询数据,这个时候需要自己写条件。
01. 在 application.yml中指定mybatis-plus的相关配置,尤其要指定xml的路径,默认在mapper下,本人仍习惯指明位置
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl# 指定mapper.xml所在的位置mapper-locations: classpath:/mapper/*.xml
02. 在Mapper中增加声明
/*** 手写语句实现分页查询* @param page 拦截器使用,当前sql中不需要* @param employee 查询对象* @return 查询结果*/Page<Employee> getEmployeeInfoByPage(@Param("page") Page<Employee> page, @Param("employee") Employee employee);
03. 添加Mapper对应的xml文件并增加对应的函数
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ssm01.mapper.EmployeeMapper"><resultMap id="baseResultMap" type="com.ssm01.pojo.Employee"><result column="SPF_UID" property="id"/><result column="Part_PartSap" property="partSap"/><result column="Part_PlateSap" property="plateSap"/><result column="SPF_Name" property="name"/></resultMap><select id="getEmployeeInfoByPage" resultMap="baseResultMap">select * from SPF_Require_Vehicle where SPF_Name = #{employee.name} and IsActvie = 0</select>
</mapper>
04. 在自己的service中增加相应的方法,调用mapper中的函数
99%的人还看了
相似问题
- django ModelSerializer自定义显示字段
- 替换sql,某个字段特定容
- Java之反射获取和赋值字段
- java mybatisplus generator 修改字段类型
- 使用用户代理字段进行浏览器检测(判断页面运行环境)
- js数组操作——对象数组根据某个相同的字段分组
- spring boot加mybatis puls实现,在新增/修改时,对某些字段进行处理,使用的@TableField()
- 【IDEA 使用easyAPI、easyYapi、Apifox helper等插件时,导出接口文档缺少代码字段注释的相关内容、校验规则的解决方法】
- mysql取出组内按照某时间最新一条数据的其他字段
- 基于geotools24.0的创建自动增长主键id字段的方法
猜你感兴趣
版权申明
本文"Mybatis-plus 使用":http://eshow365.cn/6-17649-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!
- 上一篇: 刷题笔记27——并查集
- 下一篇: arm 点灯实验代码以及现象