Mybatis plus 学习
一.什么是Mybatis-Plus
1.1.简介
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
1.2.特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作
二.Mybatis-Plus入门
2.1.导入依赖
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- mybatis-plus -->
<!-- mybatis-plus 是自己开发,并非官方的! -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
2.2.连接数据库,与mybatis一样
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
2.3.编写pojo(User类)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private Integer age;
}
2.4.编写mapper接口
//只需要继承基本的basemapper
@Repository// 将类识别为Bean,同时它还能将所标注的类中抛出的数据访问异常封装为 Spring 的数据访问异常类型。spring本身提供了一个丰富的并且是与具体的数据访问技术无关的数据访问异常结构,用于封装不同的持久层框架抛出的异常,使得异常独立于底层的框架。
public interface UserMapper extends BaseMapper<User> {
}
2.5主启动类中扫描mapper包下的所有接口
@MapperScan("com.example.demo.order.mapper") //在主启动类中扫描mapper包
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2.6在测试类中测试
@SpringBootTest
class DemoApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
测试结果
User(id=1, name=lisa, age=12)
2.6.配置日志
配置日志的原因:因为mybatis-plus中所有的sql是不可见的,如果想知道是怎么执行的,就必须要看日志。
配置日志:
#配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl //在控制台打印日志
三.CRUD扩展操作
3.1.测试插入
@Test
public void testInsert(){
User user=new User();
user.setAge(16);
user.setId(5);
user.setName("鱼七");
int result = userMapper.insert(user); //result表示影响的行数
System.out.println(result);
}
3.2.测试更新
@Test
public void testUpdate(){
User user=new User();
user.setAge(17);
user.setId(5);
user.setName("鱼七");
int result = userMapper.updateById(user); //updateById的参数是一个对象
System.out.println(result);
}
执行语句为:Preparing: UPDATE user SET name=?, age=? WHERE id=? //可以通过条件自动拼接动态sql
3.3.自动填充创建时间和修改时间
方法:
3.3.1.在实体类的字段属性上需要增加注解
public class User {
private Integer id;
private String name;
private Integer age;
@TableField(fill = FieldFill.INSERT) //只在插入的时候有操作
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE) //插入和更新的时候都有操作,如果只有更新的话,第一次插入后该字段无数据
private Date updateTime;
}
3.3.2.编写处理器来处理注解
@Component //把处理器加入到ioc容器中
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
//插入时对两个参数都起作用
public void insertFill(MetaObject metaObject) {
log.info("start insert fill ...."); //在日志打印
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
@Override
//更新时只对updateTime起作用
public void updateFill(MetaObject metaObject) {
log.info("start update fill ....");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
3.4.乐观锁
乐观锁顾名思义就是在操作时很乐观,认为操作不会产生并发问题(不会有其他线程对数据进行修改),因此不会上锁。但是在更新时会判断其他线程在这之前有没有对数据进行修改,一般会使用版本号机制
或CAS(compare and swap)算法
实现。
3.4.1版本号机制
- 取出记录时,获取当前
version
- 更新时,带上这个
version
- 执行更新时,
set version = newVersion where version = oldVersion
- 如果
version
不对,就更新失败
核心sql
update table set name = 'Aron', version = version + 1 where id = #{id} and version = #{version};
3.4.2乐观锁插件
1.先给数据库增加version字段
2.给实体类增加相应字段
@Version //乐观锁Version注解
private Integer version;
3.注册组件
// 扫描我们的 mapper 文件夹
@MapperScan("com.example.mapper")
@EnableTransactionManagement
@Configuration // 配置类
public class MyBatisPlusConfig {
// 注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
3.5查询操作
// 测试查询
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
// 测试批量查询!
@Test
public void testSelectByBatchId(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
// 按条件查询之一使用map操作
@Test
public void testSelectByBatchIds(){
HashMap<String, Object> map = new HashMap<>();
// 自定义要查询
map.put("name","小明");
map.put("age",3);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
3.6分页查询
3.6.1 在configuration配置分页组件
// 分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
3.6.2 分页插件测试
测试分页查询
@Test
public void testPage(){
// 参数一:当前页
// 参数二:页面大小
// 使用了分页插件之后,所有的分页操作也变得简单的!
Page<User> page = new Page<>(1,5);
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
System.out.println(page.getTotal()); //查询到的总数据条数
}
3.7删除操作
3.7.1根据id删除记录
// 测试删除
@Test
public void testDeleteById(){
userMapper.deleteById(1240620674645544965L);
}
// 通过id批量删除
@Test
public void testDeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(1240620674645544961L,124062067464554496
2L));
}
// 通过map删除
@Test
public void testDeleteMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","小明");
userMapper.deleteByMap(map);
3.7.2逻辑删除
逻辑删除 :再数据库中没有被移除,而是通过一个变量来让他失效! deleted = 0 => deleted = 1
管理员可以查看被删除的记录!防止数据的丢失,类似于回收站!
1.在数据表中增加一个deleted字段
2.在实体类增加deleted属性
@TableLogic //逻辑删除
private Integer deleted;
3.在config中配置逻辑删除组件
// 逻辑删除组件!
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
//在properties文件中配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
//逻辑删除sql语句:
update user set deleted=1 where id=? AND deleted=0
//加入逻辑删除后查询sql语句
select id,name,age form user where id=? AND deleted=0
四.条件构造器
4.1 查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于12
@Test
void contextLoads() {
// 查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于12
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.isNotNull("name")
.isNotNull("email")
.ge("age",12);
userMapper.selectList(wrapper).forEach(System.out::println); /
}
4.2查询特定条件的一个用户
@Test
void test2(){
// 查询名字小明
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","小明");
User user = userMapper.selectOne(wrapper); // 查询一个数据,出现多个结果使用List
System.out.println(user);
}
4.3查询范围条件内用户
@Test
void test3(){
// 查询年龄在 20 ~ 30 岁之间的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",20,30); // 区间
Integer count = userMapper.selectCount(wrapper);// 查询结果数
System.out.println(count);
}
4.4模糊查询
// 模糊查询
@Test
void test4(){
// 查询年龄在 20 ~ 30 岁之间的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
// 左和右 t%
wrapper
.notLike("name","e")
.likeRight("email","t") //%在右边,%t,以t开头
.like("name","s");//%s% 包含字母s就行
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
maps.forEach(System.out::println);
}
4.5查询结果就行排序
//测试六
@Test
void test6(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
// 通过id进行排序
wrapper.orderByAsc("id"); //根据id进行降序
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
五.代码自动生成器
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、
Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
public class CodeGenerator1 {
public static void main(String[] args) {
//创建AutoGenerator
AutoGenerator mpg = new AutoGenerator();
//设置全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
//代码生成位置
gc.setOutputDir(projectPath + "/src/main/java");
//设置生成类的命名规则
gc.setMapperName("%sMapper"); //例如UserMapper
//设置service接口的命名
gc.setServiceName("%sService"); //例如UserService
//设置service实现类的名称
gc.setServiceImplName("%sServiceImpl"); //例如UserServiceImpl
//设置controller类的名称
gc.setControllerName("%sController");
gc.setAuthor("niuliguo");
//设置主键id的配置
gc.setIdType(IdType.AUTO);//IdType.AUTO数据库自增
mpg.setGlobalConfig(gc);
//设置数据源datasource
DataSourceConfig ds=new DataSourceConfig();
//驱动
ds.setDriverName("com.mysql.cj.jdbc.Driver");
//设置url
ds.setUrl("jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC");
//设置数据库用户名
ds.setUsername("root");
//设置密码
ds.setPassword("123456");
//把datasourceConfig赋值给AutoGenerator
mpg.setDataSource(ds);
//设置package信息
PackageConfig pc=new PackageConfig();
//设置模块名称,相当于包名,在包的下面有mapper和service,controller
pc.setModuleName("order");
//设置父包
pc.setParent("com.example.demo");//com.example.demo.order
mpg.setPackageInfo(pc);
//设置策略
StrategyConfig sc=new StrategyConfig();
sc.setColumnNaming(NamingStrategy.underline_to_camel);//驼峰命名规则
sc.setNaming(NamingStrategy.underline_to_camel);
mpg.setStrategy(sc);
//执行代码的生成
mpg.execute();
}
}