简介
备注
以下所有链接版本都指3.x版本。2.x版本网址:将https://mybatis.plus/改为https://mp.baomidou.com/即可。
官网
MyBatis-Plus(中文官网:有文档和配置)
指南
https://mybatis.plus/guide
源码地址
gitee:mybatis-plus: mybatis 增强工具包,简化 CRUD 操作。 文档 http://baomidou.com
gitee示例:mybatis-plus-samples: MyBatis-Plus Samples 文档
github:GitHub - baomidou/mybatis-plus: An powerful enhanced toolkit of MyBatis for simplify development
常见问题
快速入门
代码生成器
使用:mybatis.plus
配置:mybatis.plus
使用配置
简要:mybatis.plus
详细:https://mybatis.plus/config/
类型对应
Java | SQL |
Date,LocalDateTime | datetime |
重要的类
所在路径:com\baomidou\mybatisplus\*
类 | 说明 |
BaseMapper.java | crud方法。(这是一个接口) |
ServiceImpl.java | 对BaseMapper.java的封装,实现IService接口。有:list、saveOrUpdate、count等方法。 可以直接用,或者新建类来继承此类。 |
IService.java | 这是一个接口,一般与ServiceImpl.java结合使用,例如:产品服务: //接口 public interface IProductService extends IService<Product>{ } //实现 public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService{ } 此时,就可以直接调用IService的接口来使用ServiceImpl的实现方法了。 |
Wrappers.java | 提供创建Wrapper、LambdaWrapper的静态方法。 |
ChainWrappers.java | 提供创建ChainLambdaWrapper的静态方法。 |
IService.java
Iservice.java所有方法
IService.java方法说明
方法 | 说明 |
getBaseMapper | 获得对应的baseMapper。从而可以去调用BaseMapper方法。当然,实际上IService的方法已完全包含BaseMapper的方法,无需这样做。 |
getOne | 1个参数时,若有多个值则报错。 2个参数时,若第二个参数设为false,则有多个值时不报错,取第一个。 |
lambdaQuery | 会返回一个LambdaQueryChainWrapper实例,用法见Wrapper专题。 本处示例: List<User> list = userService.lambdaQuery().eq(User::getAge, 18).list(); |
lambdaUpdate | 会返回一个LambdaUpdateChainWrapper实例,用法见Wrapper专题。可更新/删除。 本处示例: boolean update = userService.lambdaUpdate().eq(User::getAge, 18).set(User::getAge, 31).update(); boolean remove = userService.lambdaUpdate().eq(User::getAge, 18).remove(); |
list | 无参数可查询所有 |
saveBatch | 若参数为null,则返回false |
saveOrUpdate | 通过id来判断。若存在此id则更新,没有则插入。 |
参数Wrapper
可以跟LambdaQueryWrapper,例如:remove(new LambdaQueryWrapper<User>().eq(User::getName, "Tony"));
不能跟LambdaQueryChainWrapper,例如:remove(lambdaQuery().eq(User::getName, "Tony")),否则报错:
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.builder.BuilderException: Error evaluating expression 'ew.entity != null'. Cause: org.apache.ibatis.ognl.OgnlException: entity [com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: can not use this method for "getEntity"]
返回值为list
例如:list();若一项都没有,则会返回空的List,需要用list.isEmpty()判断,只用list == null判断是不够的
BaseMapper.java
BaseMapper.java所有方法
项目实例
源码地址
https://gitee.com/shapeless/demo_MybtisPlus/tree/master/MultiTable_Page
项目结构
config
package com.example.conf;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
("com.example.**.mapper")
public class MybatisPlusConfig {
/**
* 分页插件
*/
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
entity/vo
package com.example.entity;
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.Data;
import java.util.Date;
("t_question")
public class Question {
// 问答主键id
(value = "id", type = IdType.AUTO)
private Integer id;
// 学生外键id
("student_id")
private Integer studentId;
// 问题内容
private String content;
// 问题悬赏的积分
private Integer value;
}
package com.example.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
("t_student")
public class Student {
// 学生主键id
(value = "id", type = IdType.AUTO)
private Integer id;
// 学生名称
private String name;
// 学生积分数
private Integer points;
}
package com.example.vo;
import lombok.Data;
import java.io.Serializable;
public class QuestionStudentVO {
// 问答主键id
private Integer id;
// 学生外键id
private Integer studentId;
private String name;
// 问题内容
private String content;
// 问题悬赏的积分
private Integer value;
}
mapper
package com.example.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.Question;
import com.example.vo.QuestionStudentVO;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface QuestionMapper extends BaseMapper<Question> {
("SELECT t_question.*,t_student.`name` FROM t_question,t_student WHERE t_question.student_id=t_student.id")
List<QuestionStudentVO> getQuestionStudent();
("SELECT t_question.*,t_student.`name` FROM t_question,t_student WHERE t_question.student_id=t_student.id")
List<QuestionStudentVO> getQuestionStudentPage (Page<QuestionStudentVO> page);
}
package com.example.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.entity.Student;
public interface StudentMapper extends BaseMapper<Student> {
}
service
Question
package com.example.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.entity.Question;
import com.example.vo.QuestionStudentVO;
import java.util.List;
public interface QuestionService extends IService<Question> {
Page<QuestionStudentVO> getQuestionStudentPage (Page<QuestionStudentVO> page);
List<QuestionStudentVO> getQuestionStudent();
}
package com.example.service.impl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.Question;
import com.example.mapper.QuestionMapper;
import com.example.service.QuestionService;
import com.example.vo.QuestionStudentVO;
import org.springframework.stereotype.Service;
import java.util.List;
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {
//下边的两处this.baseMapper都可以用自动注入的QuestionMapper替换
//即:
//@Autowired
//private QuestionMapper questionMapper;
public List<QuestionStudentVO> getQuestionStudent() {
return this.baseMapper.getQuestionStudent();
}
public Page<QuestionStudentVO> getQuestionStudentPage (Page<QuestionStudentVO> page) {
return page.setRecords(this.baseMapper.getQuestionStudentPage (page));
}
}
Student
package com.example.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.entity.Student;
public interface StudentService extends IService<Student> {
public Student getRandomStudent();
public int getCountOfStudents();
}
package com.example.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.Student;
import com.example.mapper.StudentMapper;
import com.example.service.StudentService;
import org.springframework.stereotype.Service;
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
//下边的两处this.baseMapper都可以用自动注入的StudentMapper替换
//即:
//@Autowired
//private StudentMapper studentMapper;
public Student getRandomStudent() {
return this.baseMapper.selectOne(null);
}
public int getCountOfStudents() {
return count(null);
}
}
controller
package com.example.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.Question;
import com.example.entity.Student;
import com.example.service.QuestionService;
import com.example.service.StudentService;
import com.example.vo.QuestionStudentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
("/common")
public class CommonController {
QuestionService questionService;
StudentService studentService;
("/getRandomStudent")
public Student getRundomStudent() {
Student student = studentService.getRandomStudent();
return student;
}
("/getStudentCount")
public Integer getmStudentCount() {
Integer integer = studentService.getCountOfStudents();
return integer;
}
("/getAllQuestionWithStudent")
public Map<String, Object> getAllQuestionWithStudent() {
Map<String, Object> map = new HashMap<>();
List<QuestionStudentVO> questionStudent = questionService.getQuestionStudent();
if (questionStudent.size() == 0) {
map.put("code", 400);
} else {
map.put("code", 200);
map.put("data", questionStudent);
}
return map;
}
("/getAllQuestionWithStudentByPage/{page}/{size}")
public Map<String, Object> getAllQuestionWithStudentByPage( Integer page, Integer size) {
Map<String, Object> map = new HashMap<>();
Page<QuestionStudentVO> questionStudent = questionService.getQuestionStudentPage (new Page<>(page, size));
if (questionStudent.getRecords().size() == 0) {
map.put("code", 400);
} else {
map.put("code", 200);
map.put("data", questionStudent);
}
return map;
}
}