目录
4.开始使用(使用MyBatisPlus实现单表的CRUD)
4.2编写实体类User.java(使用lombok简化开发)
4.4新建mapper下的UserMapper接口(需要继承BaseMapper)
5.常用注解(@TableName、@TableId、@TableLogic)
官方文档:MyBatis-Plus (baomidou.com)
1.MyBatisPlus特性(较MyBatis的升级)
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作
2.数据库准备
这里我们导入官方提供的数据:建表
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
插入数据
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
3.初始化工程
新建一个SpringBoot的空项目
导入依赖:(springboot依赖,mysql数据库依赖,lombok简化实体类开发,mybatisplus依赖)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--mysql驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--lombok简化实体类开发-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--mybatis-plus启动类-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1.tmp</version>
</dependency>
3.配置application.yml
spring:
#配置数据源信息
datasource:
#配置数据源类型
type: com.zaxxer.hikari.HikariDataSource
#配置数据库信息
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&userSSL=false
mybatis-plus:
configuration:
#打印mybatisplus日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
4.开始使用(使用MyBatisPlus实现单表的CRUD)
4.1使用@MapperScan注解扫描mapper文件
在项目启动类上添加注解@MapperScan("com.mybatisplus.study.mapper")
4.2编写实体类User.java(使用lombok简化开发)
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
4.3为什么id字段使用Long类型?
因为MyBatisPlus使用了雪花算法用于生成id,没有设置的话默认为雪花算法生成主键id
4.4新建mapper下的UserMapper接口(需要继承BaseMapper<User>)
public interface UserMapper extends BaseMapper<User> {
}
4.5BaseMapper<T>是什么?
BaseMapper<T>是MyBatisPlus提供的一个接口
我们的UserMapper继承这个类便可以实现基本的增删改查
<T>为当前所对应的实体类 我们可以ctrl单击查看这个接口
/**
* Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能
* <p>这个 Mapper 支持 id 泛型</p>
*
* @author hubin
* @since 2016-01-23
*/
public interface BaseMapper<T> extends Mapper<T> {
/**
* 插入一条记录
*
* @param entity 实体对象
*/
int insert(T entity);
/**
* 根据 ID 删除
*
* @param id 主键ID
*/
int deleteById(Serializable id);
/**
* 根据 columnMap 条件,删除记录
*
* @param columnMap 表字段 map 对象
*/
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* 根据 entity 条件,删除记录
*
* @param wrapper 实体对象封装操作类(可以为 null)
*/
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
/**
* 删除(根据ID 批量删除)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* 根据 ID 修改
*
* @param entity 实体对象
*/
int updateById(@Param(Constants.ENTITY) T entity);
/**
* 根据 whereEntity 条件,更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
*/
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
/**
* 根据 ID 查询
*
* @param id 主键ID
*/
T selectById(Serializable id);
/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* 查询(根据 columnMap 条件)
*
* @param columnMap 表字段 map 对象
*/
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* 根据 entity 条件,查询一条记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询总记录数
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 entity 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
* <p>注意: 只返回第一个字段的值</p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 entity 条件,查询全部记录(并翻页)
*
* @param page 分页查询条件(可以为 RowBounds.DEFAULT)
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
<E extends IPage<T>> E selectPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录(并翻页)
*
* @param page 分页查询条件
* @param queryWrapper 实体对象封装操作类
*/
<E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}
4.6测试查询功能
我们编写一个测试类
@SpringBootTest
public class MyBatisplusTest(){
@Autowired
private UserMapper userMapper;
}
因为我们的UserMapper继承了BaseMapper这个接口,所以我们可以使用它所提供的方法
@Test
public void selectList(){
/*通过条件构造器查询一个list集合,若没有条件,则可以设置null为参数*/
List<User> list = userMapper.selectList(null);
list.forEach(System.out::println);
}
selectList即为BaseMapper所提供的查询方法,参数为条件构造器,如果没有,填写null即可
输出结果(因为我们在yml文件中配置了log-impl,所以出现出现sql语句等日志):
==> Preparing: SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0
==> Parameters:
<== Columns: id, name, age, email, is_deleted
<== Row: 4, 小明, 21, test@qq.com, 0
<== Row: 5, Billie, 24, test5@baomidou.com, 0
<== Row: 6, 小明, 23, test@qq.com, 0
<== Row: 7, 小明, 23, test@qq.com, 0
<== Row: 8, 小明, 23, test@qq.com, 0
<== Total: 5
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6fd12c5]
User(id=4, name=小明, age=21, email=test@qq.com, isDeleted=0)
User(id=5, name=Billie, age=24, email=test5@baomidou.com, isDeleted=0)
User(id=6, name=小明, age=23, email=test@qq.com, isDeleted=0)
User(id=7, name=小明, age=23, email=test@qq.com, isDeleted=0)
User(id=8, name=小明, age=23, email=test@qq.com, isDeleted=0)
此时我们便基于MyBatisPlus提供的接口查出了数据库的数据
4.7根据id删除
/**
* DELETE FROM user WHERE id=?
* 根据id删除
*/
int result = userMapper.deleteById(1L);
System.out.println(result);
因为我们设置id长度为Long,所以我们需要给后面加个L数据转换为Long类型
4.8根据id更新
public void testUpdate(){
/**
* UPDATE user SET name=?, age=? WHERE id=?
*/
//根据id修改用户信息
User user = new User();
user.setId(4L);
user.setAge(99);
user.setName("asdasa");
int update = userMapper.updateById(user);
System.out.println(update);
}
修改id为4的用户信息为年龄99,名字为asdas
4.9插入数据
@Test
public void testInsert(){
//新增用户信息
//INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
User user = new User();
user.setName("zhangsan");
user.setAge(23);
user.setEmail("asdasdasda");
int result = userMapper.insert(user);
System.out.println("result" + result);
System.out.println("id" + user.getId());
}
5.常用注解(@TableName、@TableId、@TableLogic)
@TableName
//配置数据库表名
@TableName("t_user")
public class User {
用于实体类上,用于配置数据库表名,例如实体类为User,表名为t_user
此时就需要在pubile class User{}上配置@TableName("t_user")
@TableId
@TableId(value = "uid")
private Long id;
该注解有两个参数,value和type,用于字段上
//将属性所对应的字段指定为主键 //@TableId注解的value属性用于指定主键的字段 //@TableId注解的type属性用于设置主键生成策略
type默认为雪花算法生成主键id,当我们使用需要使用数据库的主键自增时需要将type设置为
type = IdType.AUTO
@TableLogic
//逻辑删除
@TableLogic
private Integer isDeleted;
逻辑删除,我们给数据库新增字段is_deleted,默认值为0,在实体类中参数isDeleted上加@TableLogic,当我们实现删除业务时,该值从0变到1,在数据库中数据存在,执行查询方法查询条件为isDeleted为0
@TableField
//指定属性对应的字段名
@TableField("user_name")
private String name; //指定属性对应的字段名
@TableField("user_name")
private String name;
6.总结
上面所展示的只是一部分
BaseMapper中还有很多提供的方法,大家可以自己测试一下,wrapper相关的后面会继续更新文章