目录
MyBatis-Plus(简称 MP)是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为 简化开发、提高效率而生。
创建springboot项目后引入依赖:
- //mybatisplus
- <dependency>
- <groupId>com.baomidougroupId>
- <artifactId>mybatis-plus-boot-starterartifactId>
- <version>3.5.1version>
- dependency>
-
- //lombok
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- <optional>trueoptional>
- dependency>
-
- //数据库驱动
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <scope>runtimescope>
- dependency>
在application.yml配置文件中编写基本信息:
- spring:
- # 配置数据源信息
- datasource:
- # 配置数据源类型
- type: com.zaxxer.hikari.HikariDataSource
- # 配置连接数据库信息
- driver-class-name: com.mysql.cj.jdbc.Driver
- url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
- username: root
- password: 310333
- # 配置MyBatis日志
- mybatis-plus:
- configuration:
- log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
自动扫描mapper包:
- @SpringBootApplication
- @MapperScan("com.mybatisplus.mapper")
- public class MybatisplusApplication {
- public static void main(String[] args) {
- SpringApplication.run(MybatisplusApplication.class, args);
- }
- }
实体类:
- @AllArgsConstructor
- @NoArgsConstructor
- @Data
- @TableName("user") //设置实体类对应的表名
- public class User {
- //将指定字段指定为主键,设置为自动递增(如果不设置就使用雪花算法)
- @TableId(value = "id",type = IdType.AUTO)
- private Long id;
- //数据库表字段相对应
- @TableField("name")
- private String name;
- private Integer age;
- private String email;
- //逻辑删除
- @TableLogic
- private Integer isDeleted;
- }
MyBatis-Plus中的基本CRUD在内置的BaseMapper中都已得到了实现,我们可以直接使用其里面的方法,使自定义mapper继承BaseMapper即可。
我们可以使用自定义的方法,但要创建xml文件,放在resources/mapper目录下。示例:
- mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.mybatisplus.mapper.UserMapper">
- <select id="selectMapById" resultType="map">
- select id,name,age,email from user where id=#{id}
- select>
-
- <select id="selectPageVo" resultType="com.mybatisplus.pojo.User">
- select id,name,age,email from user where age>#{age}
- select>
- mapper>
UserMapper:
- @Repository
- public interface UserMapper extends BaseMapper
{ - }
测试,使用BaseMapper提供的方法:
- @SpringBootTest
- public class myBatisPlusTest {
- @Autowired
- private UserMapper userMapper;
-
- @Test
- void testInsert(){
- //插入新记录
- //INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
- userMapper.insert(new User(null,"wz",18,"110@qq.com",1));
- }
-
- @Test
- void testDelete(){
- //根据id删除记录
- //DELETE FROM user WHERE id=?
- userMapper.deleteById(1556096369749561346L);
- }
-
- @Test
- void testDeleteByMap(){
- //根据多条件删除记录
- //DELETE FROM user WHERE name = ? AND age = ?
- HashMap
map = new HashMap<>(); - map.put("name","wz");
- map.put("age",18);
- userMapper.deleteByMap(map);
- }
- @Test
- void testDeleteBatchId(){
- //根据多个id删除记录
- //DELETE FROM user WHERE id IN ( ? , ? )
- List
list = Arrays.asList(1L, 2L); - userMapper.deleteBatchIds(list);
- }
- @Test
- void testUpdate(){
- //根据id更新记录
- //UPDATE user SET name=?, age=?, email=? WHERE id=?
- userMapper.updateById(new User(3L,"zp",19,"zp@qq.com",0));
- }
- @Test
- void testSelect(){
- //根据id查询记录
- //SELECT id,name,age,email FROM user WHERE id=?
- userMapper.selectById(3L);
-
- //根据多个id查询记录
- //SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? )
- List
list = Arrays.asList(3L, 4L, 5L); - userMapper.selectBatchIds(list);
-
- //根据多条件查询记录
- //SELECT id,name,age,email FROM user WHERE name = ? AND age = ?
- HashMap
map = new HashMap<>(); - map.put("name","wz");
- map.put("age",18);
- userMapper.selectByMap(map);
-
- //查询所有记录
- //SELECT id,name,age,email FROM user
- List
users = userMapper.selectList(null); - users.forEach(System.out::println);
- }
- }
MyBatis-Plus中有一个接口 IService和其实现类 ServiceImpl,封装了常见的业务层逻辑。我们可以让自定义service接口继承Iservice接口,使用其提供的基础功能。若ServiceImpl无法满足业务需求,则可以自定义ServiceImpl。
注:IService采用 get 查询单行,remove 删除, list 查询集合,page 分页的前缀命名方式区分 Mapper层避免混淆。
UserService接口:
- public interface UserService extends IService
{ - }
UserServiceimpl:
- @Service
- public class UserServiceImpl extends ServiceImpl
implements UserService { - }
测试,使用IService提供的方法:
- @SpringBootTest
- public class serviceTest {
- @Autowired
- private UserService userService;
-
- @Test
- void testGetCount(){
- //查询记录总数
- //SELECT COUNT( * ) FROM user
- long count = userService.count();
- System.out.println(count);
- }
-
- @Test
- void testInsertBatch(){
- //批量插入新纪录
- //INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
- List
list=new ArrayList<>(); - list.add(new User(null,"wzz",28,"1@qq.com",0));
- list.add(new User(null,"zhd",12,"2@qq.com",0));
- list.add(new User(null,"lku",30,"3@qq.com",0));
- userService.saveBatch(list);
- }
- }
作用:标识实体类对应的表
举例:
- @TableName("t_user") //设置实体类对应的表名
- public class User {
- }
另外,也可以通过修改全局配置文件的方式来匹配具有固定前缀的数据库表名:
- mybatis-plus:
- global-config:
- db-config:
- # 配置MyBatis-Plus操作表的默认前缀
- table-prefix: t_
作用:标识主键字段名
示例:
- //将指定字段指定为主键,设置为自动递增的方式
- @TableId(value = "u_id",type = IdType.AUTO)
- private Long id;
常用的主键策略:
配置全局主键策略:
- mybatis-plus:
- global-config:
- db-config:
- # 配置MyBatis-Plus操作表的默认前缀
- table-prefix: t_
- # 配置MyBatis-Plus的主键策略
- id-type: auto
作用:将实体类属性与数据库表字段对应
示例:
- @TableField("u_name")
- private String name;
作用:假删除,将对应数据中代表是否被删除字段的状态修改为“被删除”,之后在数据库中仍旧能看到此条数据记录。0是未删除,1是已删除。
示例:
- //逻辑删除
- @TableLogic
- private Integer isDeleted;
添加该字段后,删除功能真正执行的是修改操作:
UPDATE t_user SET is_deleted=1 WHERE id=? AND is_deleted=0
查询功能:
SELECT id,username AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0