简介
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
愿景
我们的愿景是成为 MyBatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。
特性
无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
支持数据库
mysql 、 mariadb 、 oracle 、 db2 、 h2 、 hsql 、 sqlite 、 postgresql 、 sqlserver
达梦数据库 、 虚谷数据库 、 人大金仓数据库
使用
pom.xml
<!--mybatis-plus启动器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<!--Lombok用于简化实体开发-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>true</scope>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--Web项目-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
配置文件application.yml
spring:
#配置信息源信息
datasource:
#配置数据源类型
#type:
#配置连接数据库的各个信息
driver-class-name: com.mysql.cj.jdbc.Driver
#连接地址
url: jdbc:mysql://127.0.0.1:3306/mp?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
#密码
password: root
#用户名
username: root
注意
springboot2.0(内置JDBC5驱动),驱动类使用
driver-class-name: com.mysql.jdbc.Driver
驱动类2.1及以上(内置JDBC8驱动),驱动类使用
driver-class-name: com.mysql.cj.jdbc.Driver
否则运行的时候会有WARN信息
连接地址url
mysql5.7
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
mysql8
jdbc:mysql://localhost:3306/dataSourceName?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
MyBatisX插件
MybatisX 是一款基于 IDEA 的快速开发插件,为效率而生。
安装方法:打开 IDEA,进入 File -> Settings -> Plugins -> Browse Repositories,输入 mybatisx
搜索并安装。
连接数据库
示例连接MySQL
点击Mysql ,输入账户密码 Database 也可不填(最好填上数据库),在连接时可能会报错连接时区错误,时区问题在URL后面添加?serverTimezone=Asia/Shanghai即可连接成功
?serverTimezone=Asia/Shanghai
点击Apply 即可在页面看到
快速生成
选择表右键点击MybatisX-Generator
选择配置
点击ok即可看到文件生成成功
MybatisX自定义CURD
mapper层
mapper层编写insertSelective方法 使用的时候需要Alt+Enter键
deleteByIdAndName方法 By是根据And是和
updateNameAndGenderById
前面两个是修改的参数By是根据
selectCreateTimeAndCreateTimeByGenderBetween
查询开始时间、结束时间根据性别between是区间
selectNameOrderByIdDesc
查询姓名倒序
测试类验证
import com.yongyuankuaile.power.mapper.UserMapper;
import com.yongyuankuaile.power.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class PowerApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
//通过条件构造器查询一个List集合,若没有条件,则可以设置null为参数
List<User> list = userMapper.selectList(null);
list.forEach(System.out::println);
}
}
Mybatisplus教程
1.加入日志功能
配置文件
mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
统一CURD的使用
Mapper包XxxMapper.java
/*
* Mapper接口
* 基于Mybatis: 在Mapper接口中编写CRUD相关的方法,提供Mapper接口对应的SQL映射文件以及方法对应的SQL语句
*
* 基于MP: 让XxxMapper接口继承BaseMapper接口即可
* BaseMapper<T>:泛型指定的就是当前Mapper接口所操作的实体类类型
* */
@Mapper
public interface MpMapper extends BaseMapper<MpEmployee> {
}
实体类Employee层
/*
* 实体类
* MybatisPlus会默认使用实体类的类名到数据库中找对应的表
* */
@Data
@TableName("mp")
public class MpEmployee {
/*
* @TableId
* value: 指定表中的主键列的列明,入股实体属性名与列名一致,可以省略不指定
* type: 指定主键策略
* */
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
@TableField(value = "last_name")
private String lastName;
private String email;
private Integer gender;
private Integer age;
}
简单的增删改查操作
添加操作
@Test
void Test1() {
User user = new User();
user.setName("张三1");
user.setEmail("zhangsan1@163.com");
user.setGender(0);
int insert = userMapper.insert(user);
System.out.println("insert:"+insert);
System.out.println("id:"+user.getId());
}
根据id删除
@Test
void Test2() {
int result = userMapper.deleteById(3);
System.out.println("result:"+result);
}
键值对的方式删除
@Test
void Test2() {
HashMap<String, Object> map = new HashMap<>();
map.put("name","张三1");
map.put("age",23);
int result = userMapper.deleteByMap(map);
System.out.println("result:"+result);
}
通过id批量删除
@Test
void Test2() {
List<Long> list = Arrays.asList(1L,2L,3L);
int result = userMapper.deleteBatchIds(list);
System.out.println("result:"+result);
}
根据id进行修改
@Test
void TestUpdate() {
User user = new User();
user.setId(1L);
user.setName("张三2");
user.setEmail("zhangsan2@163.com");
user.setGender(1);
int insert = userMapper.updateById(user);
System.out.println("insert:"+insert);
System.out.println("id:"+user.getId());
}
查询通过id查询用户信息
@Test
void TestSelect() {
User user = userMapper.selectById(1L);
System.out.println("user:"+user);
}
根据多个id查询多个用户的信息
@Test
void TestSelect() {
List<Long> list = Arrays.asList(1L, 2L, 3L);
List<User> users = userMapper.selectBatchIds(list);
users.forEach(System.out::println);
}
根据条件查询
@Test
void TestSelect() {
HashMap<String, Object> map = new HashMap<>();
map.put("name","张三2");
map.put("email","zhangsan2@163.com");
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
查询所有数据
@Test
void TestSelect() {
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
通用Service接口
通用 Service CRUD 封装IService (opens new window)接口,进一步封装 CRUD 采用 get 查询单行 remove 删除 list 查询集合 page 分页 前缀命名方式区分 Mapper 层避免混淆,
实体类
public interface UserService extends IService<User> {
}
Impl层
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
implements UserService{
}
//查询总记录数
@Test
void Test() {
//查询总记录数
long count = userService.count();
System.out.println("总记录数:"+count);
}
批量添加
@Test
void TestSaveBathch() {
ArrayList<User> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
User user = new User();
user.setName("爱你"+i);
user.setEmail("aini@163.com"+i);
list.add(user);
}
boolean b = userService.saveBatch(list);
System.out.println(b);
}
批量修改
@Test
public void bach1(){
List<User> listuser=new ArrayList<User>();
for(int i=1;i<6;i++){
User user= new User();
user.setId((long)i);
user.setUserName(i&