一.说明
Mybatis-Plus是一个Mybatis框架的增强插件,根据官方描述,MP只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑.并且只需简单配置,即可快速进行 CRUD 操作,从而节省大量时间.代码生成,分页,性能分析等功能一应俱全,最新已经更新到了3.1.1版本了,3.X系列支持lambda语法,让我在写条件构造的时候少了很多的"魔法值",从代码结构上更简洁了.
二.项目环境
- MyBatis-Plus版本: 3.1.0
- SpringBoot版本:2.1.5
- JDK版本:1.8
Maven依赖如下:
org.springframework.boot spring-boot-starter-webmysql mysql-connector-javaruntime org.projectlombok lomboktrue org.springframework.boot spring-boot-starter-testtest com.baomidou mybatis-plus-boot-starter3.1.0 com.alibaba druid1.1.6
配置如下:
# 配置端口
server:
port: 8081
spring:
# 配置数据源
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mp_student?useUnicode=true&characterEncoding=utf-8
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
# mybatis-plus相关配置
mybatis-plus:
# xml扫描,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置)
mapper-locations: classpath:mapper
@Configuration
public class MybatisPlusConfig {
@Bean
public PerformanceInterceptor performanceInterceptor() {
return new PerformanceInterceptor();
}
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
编写Entity类
@Data
@TableName("user_info")//@TableName中的值对应着表名
public class UserInfoEntity {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String skill;
private String evaluate;
private Long fraction;
}
编写Dao类
public interface UserInfoDao extends baseMapper{ }
编写Service类
public interface UserInfoService extends IService{ }
编写ServiceImpl类
@Service @Transactional public class UserInfoSerivceImpl extends ServiceImplimplements UserInfoService { }
四.MyBatis-Plus基础演示
这里我们看到,service中我们没有写任何方法,MyBatis-Plus官方封装了许多基本CRUD的方法,可以直接使用大量节约时间,MP共通方法详见IService,ServiceImpl,baseMapper源码,写入操作在ServiceImpl中已有事务绑定,这里我们举一些常用的方法演示.
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {
@Autowired
private UserInfoService userInfoService;
@RequestMapping("/getInfo")
public UserInfoEntity getInfo(String userId){
UserInfoEntity userInfoEntity = userInfoService.getById(userId);
return userInfoEntity;
}
@RequestMapping("/getList")
public List getList(){
List userInfoEntityList = userInfoService.list();
return userInfoEntityList;
}
@RequestMapping("/getInfoListPage")
public IPage getInfoListPage(){
//需要在Config配置类中配置分页插件
IPage page = new Page<>();
page.setCurrent(5); //当前页
page.setSize(1); //每页条数
page = userInfoService.page(page);
return page;
}
@RequestMapping("/getListMap")
public Collection getListMap(){
Map map = new HashMap<>();
//kay是字段名 value是字段值
map.put("age",20);
Collection userInfoEntityList = userInfoService.listByMap(map);
return userInfoEntityList;
}
@RequestMapping("/saveInfo")
public void saveInfo(){
UserInfoEntity userInfoEntity = new UserInfoEntity();
userInfoEntity.setName("小龙");
userInfoEntity.setSkill("JAVA");
userInfoEntity.setAge(18);
userInfoEntity.setFraction(59L);
userInfoEntity.setevaluate("该学生是一个在改BUG的码农");
userInfoService.save(userInfoEntity);
}
@RequestMapping("/saveInfoList")
public void saveInfoList(){
//创建对象
UserInfoEntity sans = new UserInfoEntity();
sans.setName("Sans");
sans.setSkill("睡觉");
sans.setAge(18);
sans.setFraction(60L);
sans.setevaluate("Sans是一个爱睡觉,并且身材较矮骨骼巨大的骷髅小胖子");
UserInfoEntity papyrus = new UserInfoEntity();
papyrus.setName("papyrus");
papyrus.setSkill("JAVA");
papyrus.setAge(18);
papyrus.setFraction(58L);
papyrus.setevaluate("Papyrus是一个讲话大声、个性张扬的骷髅,给人自信、有魅力的骷髅小瘦子");
//批量保存
List list =new ArrayList<>();
list.add(sans);
list.add(papyrus);
userInfoService.saveBatch(list);
}
@RequestMapping("/updateInfo")
public void updateInfo(){
//根据实体中的ID去更新,其他字段如果值为null则不会更新该字段,参考yml配置文件
UserInfoEntity userInfoEntity = new UserInfoEntity();
userInfoEntity.setId(1L);
userInfoEntity.setAge(19);
userInfoService.updateById(userInfoEntity);
}
@RequestMapping("/saveOrUpdateInfo")
public void saveOrUpdate(){
//传入的实体类userInfoEntity中ID为null就会新增(ID自增)
//实体类ID值存在,如果数据库存在ID就会更新,如果不存在就会新增
UserInfoEntity userInfoEntity = new UserInfoEntity();
userInfoEntity.setId(1L);
userInfoEntity.setAge(20);
userInfoService.saveOrUpdate(userInfoEntity);
}
@RequestMapping("/deleteInfo")
public void deleteInfo(String userId){
userInfoService.removeById(userId);
}
@RequestMapping("/deleteInfoList")
public void deleteInfoList(){
List userIdlist = new ArrayList<>();
userIdlist.add("12");
userIdlist.add("13");
userInfoService.removeByIds(userIdlist);
}
@RequestMapping("/deleteInfoMap")
public void deleteInfoMap(){
//kay是字段名 value是字段值
Map map = new HashMap<>();
map.put("skill","删除");
map.put("fraction",10L);
userInfoService.removeByMap(map);
}
}
五.MyBatis-Plus的QueryWrapper条件构造器
当查询条件复杂的时候,我们可以使用MP的条件构造器,请参考下面的QueryWrapper条件参数说明
下面我们来举一些常见的示例
@RestController
@RequestMapping("/userInfoPlus")
public class UserInfoPlusController {
@Autowired
private UserInfoService userInfoService;
@RequestMapping("/getInfoListPlus")
public Map getInfoListPage(){
//初始化返回类
Map result = new HashMap<>();
//查询年龄等于18岁的学生
//等价SQL: SELECT id,name,age,skill,evaluate,fraction FROM user_info WHERe age = 18
QueryWrapper queryWrapper1 = new QueryWrapper<>();
queryWrapper1.lambda().eq(UserInfoEntity::getAge,18);
List userInfoEntityList1 = userInfoService.list(queryWrapper1);
result.put("studentAge18",userInfoEntityList1);
//查询年龄大于5岁的学生且小于等于18岁的学生
//等价SQL: SELECt id,name,age,skill,evaluate,fraction FROM user_info WHERe age > 5 AND age <= 18
QueryWrapper queryWrapper2 = new QueryWrapper<>();
queryWrapper2.lambda().gt(UserInfoEntity::getAge,5);
queryWrapper2.lambda().le(UserInfoEntity::getAge,18);
List userInfoEntityList2 = userInfoService.list(queryWrapper2);
result.put("studentAge5",userInfoEntityList2);
//模糊查询技能字段带有"画"的数据,并按照年龄降序
//等价SQL: SELECt id,name,age,skill,evaluate,fraction FROM user_info WHERe skill LIKE '%画%' ORDER BY age DESC
QueryWrapper queryWrapper3 = new QueryWrapper<>();
queryWrapper3.lambda().like(UserInfoEntity::getSkill,"画");
queryWrapper3.lambda().orderByDesc(UserInfoEntity::getAge);
List userInfoEntityList3 = userInfoService.list(queryWrapper3);
result.put("studentAgeSkill",userInfoEntityList3);
//模糊查询名字带有"小"或者年龄大于18的学生
//等价SQL: SELECt id,name,age,skill,evaluate,fraction FROM user_info WHERe name LIKE '%小%' OR age > 18
QueryWrapper queryWrapper4 = new QueryWrapper<>();
queryWrapper4.lambda().like(UserInfoEntity::getName,"小");
queryWrapper4.lambda().or().gt(UserInfoEntity::getAge,18);
List userInfoEntityList4 = userInfoService.list(queryWrapper4);
result.put("studentOr",userInfoEntityList4);
//查询评价不为null的学生,并且分页
//等价SQL: SELECt id,name,age,skill,evaluate,fraction FROM user_info WHERe evaluate IS NOT NULL LIMIT 0,5
IPage page = new Page<>();
page.setCurrent(1);
page.setSize(5);
QueryWrapper queryWrapper5 = new QueryWrapper<>();
queryWrapper5.lambda().isNotNull(UserInfoEntity::getevaluate);
page = userInfoService.page(page,queryWrapper5);
result.put("studentPage",page);
return result;
}
}
六.自定义SQL
引入Mybatis-Plus不会对项目现有的 Mybatis 构架产生任何影响,而且Mybatis-Plus支持所有 Mybatis 原生的特性,这也是我喜欢使用它的原因之一,由于某些业务复杂,我们可能要自己去写一些比较复杂的SQL语句,我们举一个简单的例子来演示自定义SQL.
示例:查询大于设置分数的学生(分数为动态输入,且有分页)
编写Mapper.xml文件
SELECT * FROM user_info WHERe fraction > #{fraction}
在DAO中加入方法
IPageselectUserInfoByGtFraction(IPage page, Long fraction);
在service加入方法
IPageselectUserInfoByGtFraction(IPage page,Long fraction);
在serviceImpl加入方法
@Override public IPageselectUserInfoByGtFraction(IPage page, Long fraction) { return this.baseMapper.selectUserInfoByGtFraction(page,fraction); }
在Controller中测试
@RequestMapping("/getInfoListSQL")
public IPage getInfoListSQL(){
//查询大于60分以上的学生,并且分页
IPage page = new Page<>();
page.setCurrent(1);
page.setSize(5);
page = userInfoService.selectUserInfoByGtFraction(page,60L);
return page;
}
七.项目源码
项目源码:
https://gitee.com/liselotte/spring-boot-mp-demo
个人确实很喜欢用MyBatis-Plus,不仅节约时间,代码也简洁干净,它给了我那时候从SSM到SpringBoot过度的那种感觉
嗯,这玩意真香~



