后端|Mybatis-plus实现数据库的增删改查操作

目录
1、MybatisPlus简介
2、MybatisPlus注解介绍
3、常用方法
4、SpringBoot整合MybatisPlus实现增删改查的一个简单Demo
【后端|Mybatis-plus实现数据库的增删改查操作】5、参考资料
1、MybatisPlus简介 Mybatis和MybatisPlus都是非常流行的持久层框架。mybatis可以直接在xml或注解中通过SQL语句操作数据库,很是灵活。但是其操作都要通过SQL语句进行,就必须写大量的xml文件或者注解sql语句,很是麻烦。而mybatis-plus就很好的解决了这个问题。
Mybatis-Plus(简称MP)是 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。关于mybatis-plus的更多介绍及特性,可以参考mybatis-plus官网
mybatis-plus已经封装好了一些crud方法,我们不需要再写SQL语句了,直接调用这些方法就行

2、MybatisPlus注解介绍

  • @TableId 关联主键,可以通过type属性指定是否自增
  • @TableName 通过value属性关联表名,当类名与表名一致时,value属性可省写
  • @TableField 关联表字段,如果属性名称与字段名称一致则此注解可以省写(包含驼峰规则)

3、常用方法 MybatisPlus常用方法可以去看BaseMapper这个接口。BaseMapper这个接口里面封装了一些常用的sql。
public interface BaseMapper extends Mapper { int insert(T entity); int deleteById(Serializable id); int deleteByMap(@Param("cm") Map columnMap); int delete(@Param("ew") Wrapper wrapper); int deleteBatchIds(@Param("coll") Collection idList); int updateById(@Param("et") T entity); int update(@Param("et") T entity, @Param("ew") Wrapper updateWrapper); T selectById(Serializable id); List selectBatchIds(@Param("coll") Collection idList); List selectByMap(@Param("cm") Map columnMap); T selectOne(@Param("ew") Wrapper queryWrapper); Integer selectCount(@Param("ew") Wrapper queryWrapper); List selectList(@Param("ew") Wrapper queryWrapper); List selectMaps(@Param("ew") Wrapper queryWrapper); List selectObjs(@Param("ew") Wrapper queryWrapper); > E selectPage(E page, @Param("ew") Wrapper queryWrapper); > E selectMapsPage(E page, @Param("ew") Wrapper queryWrapper); }
Wrapper为条件查询构造器,QueryWrapper为Wrapper的一个实现方法。主要是用来进行多个where条件的拼接。
例如:
QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.gt("age", 10).eq("sex", "女"); //年龄大于10且性别为“女"

Wrapper中的方法 含义
ge
大于等于

gt
表示大于

le
小于等于

lt
小于

eq
等于

ne
不等于

between
范围 between("age",20,30); 年龄范围[20,30]


4、SpringBoot整合MybatisPlus实现增删改查的一个简单Demo 源码:https://gitee.com/wulinchun/mybatis-plus.git(dev分支)
4.1、目录结构 后端|Mybatis-plus实现数据库的增删改查操作
文章图片

后端|Mybatis-plus实现数据库的增删改查操作
文章图片


4.2、代码 4.2.1、xml&yml配置
pom.xml
4.0.0org.springframework.boot spring-boot-starter-parent 2.2.2.RELEASE org.example mybatis-plus 1.0-SNAPSHOT8 8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test com.baomidou mybatis-plus-boot-starter 3.4.0 com.baomidou mybatis-plus-generator 3.4.0 org.projectlombok lombok 1.18.20 provided com.microsoft.sqlserver mssql-jdbc mysql mysql-connector-java 5.1.26 org.springframework.boot spring-boot-maven-plugin true

application.yml
server: port: 8080spring: profiles: active: dev#使用application-dev.yml里面的配置

application-dev.yml
server: port: 8080 spring: datasource: name: mybatis_plus url: jdbc:mysql://localhost:3306/mydb?serverTimezone=UTC&characterEncoding=utf8 username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver mybatis: mapper-locations: classpath:mapper/*.xml #注意:一定要对应mapper映射xml文件的所在路径 type-aliases-package: com.mybatisplus.entity # 注意:对应实体类的路径mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印mybatis-plus的sql语句

ScoreMapper.xml

StudentMapper.xml


4.2.2、实体类
Score.java
package com.mybatisplus.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author: wu linchun * @time: 2021/6/6 11:34 * @description: */ @Data @TableName("t_score") @NoArgsConstructor @AllArgsConstructor public class Score { @TableField("sno") private int sno; @TableField("subject") private String subject; @TableField("score") private int score; }

Student.java
package com.mybatisplus.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * @author: Wu Linchun * @date: 2021/06/04/10:25 * @Description: **/ @Data @TableName("t_student") @NoArgsConstructor @AllArgsConstructor public class Student implements Serializable { @TableId @TableField("sno") private int sno; @TableField("sname") private String sname; @TableField("age") private int age; @TableField("sex") private String sex; @TableField("sclass") private String sclass; }

StudentScoreVO.java 注:该实体类为映射t_student表和t_score表联合查询的结果

package com.mybatisplus.entity.vo; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * @author: wu linchun * @time: 2021/6/6 11:42 * @description: */ @Data @NoArgsConstructor @AllArgsConstructor public class StudentScoreVO implements Serializable { @TableField("sno") private int sno; @TableField("sname") private String sname; @TableField("subject") private String subject; @TableField("score") private int score; }


4.2.3、接口&实现类
IScoreMapper.java

package com.mybatisplus.mapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.mybatisplus.entity.Student; import com.mybatisplus.entity.vo.StudentScoreVO; import javafx.scene.control.Pagination; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Component; import java.util.List; /** * @description: * @author: wu linchun * @time: 2021/6/6 11:49 */ @Component("iScoreMapper") public interface IScoreMapper extends BaseMapper { /** * 获取学生成绩并分页显示 * @return */ @Select("select tst.sno,tst.sname,tsc.subject,tsc.score from t_student tst,t_score tsc where tst.sno=tsc.sno") List getScore(); /** * 分页显示学生成绩 * @param * @return */ @Select("select tst.sno,tst.sname,tsc.subject,tsc.score from t_student tst,t_score tsc where tst.sno=tsc.sno") IPage getByPage(Page studentScoreVOPage,QueryWrapper queryWrapper); @Select("select count(*) from t_student tst,t_score tsc where tst.sno=tsc.sno") int getCount(); }

IStudentMapper.java

package com.mybatisplus.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.mybatisplus.entity.Student; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Component; /** * @author: Wu Linchun * @date: 2021/06/04/14:48 * @Description: **/ @Component("iStudentMapper") public interface IStudentMapper extends BaseMapper { }

IScoreService.java

package com.mybatisplus.service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.mybatisplus.entity.vo.StudentScoreVO; import javafx.scene.control.Pagination; import java.util.List; /** * @description: * @author: wu linchun * @time: 2021/6/6 11:55 */public interface IScoreService { /** * * @return */ List getScore(); /** *分页显示 * @param * @return */ IPage getByPage(Page studentScoreVOPage, QueryWrapper queryWrapper); /** * * @return */ int getCount(); }

IStudentService.java

package com.mybatisplus.service; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.mybatisplus.entity.Student; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import java.util.List; /** * @author: Wu Linchun * @date: 2021/06/04/14:02 * @Description: **/public interface IStudentService { /** * 根据唯一性主键进行查询sno是唯一性主键 * * @param sno * @return */ Student getBySno(int sno); /** * 查询全部 * * @return */ List getAll(); /** * 根据性别和年龄查询 * * @param sex * @param age * @return */ List getBySexAge(String sex, int age); /** * 范围&多条件查询 * * @param age * @return */ List getStudentsByScope(int age); /** * 添加学生 * * @param student * @return */ int insertStudent(Student student); /** * 根据指定条件删除 * * @param sno * @return */ int deleteBySno(int sno); /** * 根据多个指定条件删除 * * @param sclass * @param sex * @return */ int deleteBySclass_sex(String sclass, String sex); /** * 更新 * * @param student * @return */ int updateStudent(Student student); /** * 获取表中总记录数 * @return */ int getCount(); }

ScoreServiceImpl.java

package com.mybatisplus.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.mybatisplus.entity.vo.StudentScoreVO; import com.mybatisplus.mapper.IScoreMapper; import com.mybatisplus.service.IScoreService; import javafx.scene.control.Pagination; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import java.util.List; /** * @author: wu linchun * @time: 2021/6/6 11:56 * @description: */ @Service public class ScoreServiceImpl implements IScoreService { @Autowired @Qualifier("iScoreMapper") private IScoreMapper iScoreMapper; @Override public List getScore() { return iScoreMapper.getScore(); }@Override public IPage getByPage(Page studentScoreVOPage, QueryWrapper queryWrapper) { return iScoreMapper.getByPage(studentScoreVOPage, queryWrapper); }@Override public int getCount() { return iScoreMapper.getCount(); } }

StudentServiceImpl.java

package com.mybatisplus.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.mybatisplus.entity.Student; import com.mybatisplus.mapper.IStudentMapper; import com.mybatisplus.service.IStudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author: Wu Linchun * @date: 2021/06/04/14:55 * @Description: **/ @Service public class StudentServiceImpl implements IStudentService {@Autowired @Qualifier("iStudentMapper") private IStudentMapper iStudentMapper; @Override public Student getBySno(int sno) { return iStudentMapper.selectById(sno); }@Override public List getAll() { return iStudentMapper.selectList(null); }@Override public List getBySexAge(String sex, int age) { Map map = new HashMap<>(); map.put("sex", sex); map.put("age", age); return iStudentMapper.selectByMap(map); }@Override public List getStudentsByScope(int age) { QueryWrapper queryWrapper = new QueryWrapper<>(); //ge表示大于等于、gt表示大于、le表示小于等于、lt表示小于 //eq等于、ne不等于 //between范围 between("age",20,30); 年龄范围20~30 //查询年龄20-30范围 1.代表字段2.代表开始值3.代表结束值 /* queryWrapper.gt("age",age); queryWrapper.gt("age",10); //年龄大于10 queryWrapper.ge("age",10); //年龄大于等于10 queryWrapper.le("age",10); //年龄小于等于10 queryWrapper.lt("age",10); //年龄小于10 queryWrapper.eq("age",10); //年龄等于10 queryWrapper.ne("age",10); //年龄不等于10 queryWrapper.between("age",20,30); //年龄介于20~30之间*/ queryWrapper.gt("age", 10).eq("sex", "女"); //年龄大于10且性别为“女" return iStudentMapper.selectList(queryWrapper); }@Override public int insertStudent(Student student) { return iStudentMapper.insert(student); }@Override public int deleteBySno(int sno) { QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("sno", sno); return iStudentMapper.delete(queryWrapper); }/** * 根据班级和性别删除 * * @param sclass * @param sex * @return */ @Override public int deleteBySclass_sex(String sclass, String sex) { Map map = new HashMap<>(); map.put("sclass", sclass); map.put("sex", sex); return iStudentMapper.deleteByMap(map); }@Override public int updateStudent(Student student) { QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("sno", student.getSno()); return iStudentMapper.update(student, queryWrapper); }@Override public int getCount() { QueryWrapper queryWrapper=new QueryWrapper<>(); queryWrapper.eq("sex","男"); // return iStudentMapper.selectCount(null); //null为获取表中总记录数 return iStudentMapper.selectCount(queryWrapper); //获取指定条件的记录数 } }


4.2.4、配置类
MybatisPlusConfig.java

package com.mybatisplus.config; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author: wu linchun * @time: 2021/6/6 12:13 * @description: mybatis-plus分页插件配置 */ @Configuration public class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); }}


4.2.5、测试类
MyControllerTest.java

package com.mybatisplus.test; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.mybatisplus.entity.Student; import com.mybatisplus.entity.vo.StudentScoreVO; import com.mybatisplus.service.IStudentService; import com.mybatisplus.service.impl.ScoreServiceImpl; import com.mybatisplus.service.impl.StudentServiceImpl; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author: wu linchun * @time: 2021/6/5 20:31 * @description: */ @RunWith(SpringRunner.class) @SpringBootTest //由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。 @WebAppConfiguration public class MyControllerTest { @Autowired @Qualifier("studentServiceImpl") private StudentServiceImpl studentServiceImpl; @Autowired @Qualifier("scoreServiceImpl") private ScoreServiceImpl scoreServiceImpl; @Test public void testAdd() { int sno = 20160001; for (int i = 0; i < 10; i++) { Student student = new Student(sno++, "张三", 20, "男", "2016222"); if (studentServiceImpl.insertStudent(student) == 1) { System.out.println("添加成功"); } else { System.out.println("添加失败"); } } }@Test public void testDeleteBySno() { if (studentServiceImpl.deleteBySno(20160009) == 1) { System.out.println("删除成功"); } else { System.out.println("删除失败"); } }@Test public void testDeleteBySclass_sex() { if (studentServiceImpl.deleteBySclass_sex("2016221", "男") == 1) { System.out.println("删除成功"); } else { System.out.println("删除失败"); } }@Test public void testGetAll() { List studentList = new ArrayList(); studentList = studentServiceImpl.getAll(); for (Student student : studentList) { System.out.println(studentList.toString()); } }@Test public void testGetStudentsByScope() { List studentList = studentServiceImpl.getStudentsByScope(10); for (Student student : studentList) { System.out.println(studentList.toString()); } }@Test public void testUpdateStudent() { Student student = new Student(20160010, "HHH", 20, "男", "2016222"); if (studentServiceImpl.updateStudent(student) == 1) { System.out.println("更新成功"); } else { System.out.println("更新失败"); } }@Test public void testGetBySno() { Student student = studentServiceImpl.getBySno(20160003); System.out.println(student.toString()); }@Test public void testGetCount() { System.out.println(studentServiceImpl.getCount()); }@Test public void testGetScore() { List studentScoreVOList = scoreServiceImpl.getScore(); for (StudentScoreVO studentScoreVO : studentScoreVOList) { System.out.println(studentScoreVO.toString()); } }@Test public void testGetByPage() { int curr = 0, size = 3; while (curr <= scoreServiceImpl.getCount() / 3 + 1) { Page page = new Page<>(curr, size); System.out.println(curr + " " + size); scoreServiceImpl.getByPage(page, null).getRecords().forEach(System.out::println); curr++; System.out.println("------------------------------------------------"); } }}

由于在yml中增加了打印MybatisPlus的sql配置,因此执行时可以在控制台看到输出的MybatisPlus封装的sql语句。
后端|Mybatis-plus实现数据库的增删改查操作
文章图片


5、参考资料
MyBatis Plus 简单介绍 - 知乎 (zhihu.com)
mybatis plus实现某种条件查询 - 谢世林 - 博客园 (cnblogs.com)
mybatis-plus的sql语句打印问题_猿,码的博客-CSDN博客_mybatisplus打印sql语句
mybatis-plus实现多表联查 - 白衣风云 - 博客园 (cnblogs.com)
MyBatis-Plus_分页查询_Gblfy_Blog-CSDN博客_mybatis-plus分页查询
Mybatis-plus中sql语句LT、LE、EQ、NE、GE、GT的意思 - 潘向福 - 博客园 (cnblogs.com)

    推荐阅读