创建SpringBoot工程,使用mybatis-plus框架
SpringBoot中使用Mybatis-plus
1. 创建SpringBoot工程
选择MySQL的driver
2. 加入maven依赖
mybatis-plus依赖
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.1</version> </dependency>
完整的配置文件如下:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.4</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.changsha</groupId> <artifactId>mybatis-plus</artifactId> <version>0.0.1-SNAPSHOT</version> <name>mybatis-plus</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> <version>8.0.24</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
3. 加入数据库的信息
在resources资源目录下创建apllication.yml
的配置文件,加入数据库的配置信息。也可以在这个配置文件中配置日志信息
这种配置文件是语法和python一样有制表符来进行分割,不要乱加tab,不然找不到包
# 数据库信息 spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/study username: root password: 123456 # 开启配置 mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
4. 创建实体类(框架会根据实体类的信息来获取数据表的信息)
数据表数据如下:
实体类如下:
package com.changsha.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; public class Student { // 指定主键,类型为自动增长 @TableId(value = "id", type = IdType.AUTO) private Integer id; private String name; private Integer age; public Student() { } public Student(Integer id, String name, Integer age) { this.id = id; this.name = name; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
以上实体类给出了数据表的信息:
实体类的类名对应了数据表的表名,表名为student
实体类的属性名对应数据表的列名,列名为id,name,age
如果实体类名字和数据表中名字不对应使用注解来解决
实体名和表名不同使用@TableName注解
这里@TableName说明了表名
属性名和列名不同使用@TableField注解
在姓名属性上加入注解,注解中的value属性说明了表列的名字。说明姓名属性对应数据表中的name列
实体名转换为表信息的规则★
mybatis-plus实际是根据你的实体类来获取数据库表的信息
mybatis-plus中实体类中名子转换为数据库名字的方法是在所有大写字母前加上_
,例如属性名studentAR
被转换为stdent_a_r
因为mysql不区分大小写所以a和r被转换为小写也无所谓。
表名为
产生了找不到表的错误,可以看到表名是student_a_r
因为有这种转换,所以建议在实体类中用驼峰命名法,在数据库表中用_
分隔法
例如实体类中studentName在数据表中是student_name
主键类型
- none没有主键
- auto自动增长(mysql,sql server)
- input手工输入
分布式中用的长id(使用雪花算法生成)
都会生成很长的id,保证id是唯一的
- id_worker:实体类用Long id,表的列用bigint,int类型大小不够
- id_worker_str实体类使用String id,表的列使用varchar 50
- uuid实体类使用String id,列使用varchar50
uuid生成的id是最长的,实际分布式情况下大多数用id_worker
5. 创建继承BaseMapper< T >的接口
1)创建mapper接口
package com.changsha.Mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.changsha.entity.Student; public interface StudentMapper extends BaseMapper<Student> { /* 在BaseMapper中已经实现了很多CURD方法 类中也可以自己添加方法 */ //自定义方法 public List<Student> selfSelect(); }
这个接口可以什么方法都不声明,因为在BaseMapper类中继承了很多的CRUD(CRUD是指在做计算处理时的增加Create、读取查询Retrieve、更新Update和删除Delete几个单词的首字母简写)方法。
2)在SpringBoot的启动类中加入扫描mapper的注解
3)实现自己加上的方法
现在来实现自定义的方法,实现方法和mybatis是一样的,使用mapper配置文件来对方法注入sql语句
- 先在资源目录resource下的xml目录下创建mapper配置文件。文件名和mapper接口名一样
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace:必须有值,自定义的唯一字符串 推荐使用:dao 接口的全限定名称 语句的id建议和接口方法的名字相同 --> <mapper namespace="com.changsha.Mapper.StudentMapper"> <select id="selfSelect" resultType="com.changsha.entity.Student"> SELECT id,name,age from student </select> </mapper>
- 在数据库配置文件中加入扫描mapper配置文件的扫描器
这就完成了自定义的方法
6. 创建测试方法测试数据库操作
package com.changsha.mybatisplus; import com.changsha.Mapper.StudentMapper; import com.changsha.entity.Student; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import javax.annotation.Resource; import java.util.List; @SpringBootTest class MybatisPlusApplicationTests { // 自动注入 @Resource private StudentMapper studentDao; @Test void contextLoads() { } @Test public void testMethed(){ //自定义的方法 List<Student> students = studentDao.selfSelect(); students.forEach(student -> System.out.println(student)); //继承自BaseMapper的方法 Student student = studentDao.selectById(8); } }
对于查询的wrapper中第二个参数
null2isnull, 在有查询参数值为空时(“age”,null):
- null2isnull值为true时,会在sql的where中加入 age is null的条件
- 为false时直接忽略掉age这个查询条件
between包含两边的值
not between不包含两边的值
AR(在实体类中调用Dao方法)
前3个步骤和上面都是一样的
4. 创建实体类(继承Model类)
通过继承Model可以将实体类自身具有操作数据库的方法,这些方法有参数则根据参数进行操作,没有参数的情况下根据实体类属性值来进行操作。
package com.changsha.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.extension.activerecord.Model; //实体名和表名不一样,需要用注解指明表的名称 @TableName(value = "student") public class StudentAR extends Model<StudentAR> { // 说明主键 @TableId(value = "id", type = IdType.AUTO) private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
5. 创建Mapper接口
mapper接口是必须要创建的
如果没有这个接口就会出现如下报错,找不到实体类
com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: com.changsha.entity.StudentAR Not Found TableInfoCache.
1)创建接口
package com.changsha.Mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.changsha.entity.StudentAR; public interface StudentARMapper extends BaseMapper<StudentAR> { }
2)加入扫描
在spring-boot的启动类中加入扫描
6. 测试方法
@Test public void testAR(){ StudentAR studentDao = new StudentAR(); //有参数就用参数 StudentAR res1 = studentDao.selectById(3); System.out.println(res1); //没参数就用实体类的属性值 studentDao.setId(4); StudentAR res2 = studentDao.selectById(); System.out.println(res2); }
AR和直接使用区别
- AR是把DAO操作加在了实体类中
直接实现是把DAO操作加在了接口类中 - AR的对象需要直接手动通过注解创建
mybatis-plus框架会实现Mapper接口,所以可以通过类型注入的方式从框架自动获取DAO对象。
查询构造器Warpper使用
在调用查询方法时,发现多条件查询时用的参数是Warpper。这个类会生成选择的条件,也就是where以后的语句。
创建方法
QueryWrapper(LambdaQueryWrapper)和UpdateWrapper(LambdaUpdateWrapper)的父类用于生成sql的where条件,entity属性也用于生成sql的where条件。MP3.x开始支持lambda表达式,LambdaQueryWrapper,.LambdaUpdateWrapper支持lambda表达式的构造查询条件。
QueryWrapper<Student> wrapper = new QueryWrapper<>();
添加条件
allEq
allEq(map,boolean)
第二个参数为boolean值
true:处理null值,where 条件加入 字段 is null
false:忽略null ,不作为where 条件
eq
eq("列名",值)
ne
ne("列名",值)
gt
ge
lt
小于
le
小于等于
between
between("列名",开始值,结束值) qw.between("age", 22, 28); // where age >= 12 and age < 28
notBetween
notBetween(不在范围区间内)
like , no like
like 匹配某个值 notLike 不匹配某个值
likeLeft, likeRight
likeLeft "%值" likeRight "%值"
isNULL, isNotNull
in,notIn
inSql,notInSql
inSql() : 使用子查询
notInSql() : 使用子查询
groupBy
groupBy:分组
orderByAsc,orderByDesc,orderBy
/** * order :指定字段和排序方向 * * boolean condition : 条件内容是否加入到 sql语句的后面。 * true:条件加入到sql语句 * FROM student ORDER BY name ASC * * false:条件不加入到sql语句 * FROM student */ @Test public void testOrder(){ QueryWrapper<Student> qw = new QueryWrapper<>(); qw.orderBy(true,true,"name") .orderBy(true,false,"age") .orderBy(true,false,"email"); // name asc, age desc , email desc //FROM student ORDER BY name ASC , age DESC , email DESC print(qw); }
or ★
last
last : 拼接sql语句到MP的sql语句的最后
exists,notExists
exists : 判断条件
notExists
分页★
最新版本(3.5.1)的分页插件难配得一批,搞了两三小时(主要问题是分页插件无效,同记录数和总页数全是0),下面记录一下分页插件使用
1. 加入依赖
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-extension</artifactId> <version>3.5.1</version> </dependency>
我的mybatis-plus也是3.5.1版本的,这里如果版本不同可能会出现版本不同的冲突
2. 创建配置类
这个类就相当于配置文件,又了这个类以后就可以把ScanMapper注解写在配置类中,如何在通过Impor注解导入到启动类中。
配置类
package com.changsha.config; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @MapperScan(value = "com.changsha.Mapper")//mapper文件的包 public class PageConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } }
在启动类上引入子配置类
至此分页插件配置完成
3. 使用插件
package com.changsha.mybatisplus; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.changsha.Mapper.StudentMapper; import com.changsha.entity.Student; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import javax.annotation.Resource; import java.util.List; @SpringBootTest class MybatisPlusApplicationTests { // 自动注入 @Resource private StudentMapper studentDao; @Test public void testPage(){ QueryWrapper<Student> qw = new QueryWrapper<>(); qw.gt("age",1); qw.orderByAsc("id"); IPage<Student> page = new Page<>(); page.setCurrent(1);//当前页 page.setSize(4);//设置页面大小 IPage<Student> pageResult = studentDao.selectPage(page,qw); // IPage<Student> pageResult = studentDao.selectPage(new Page<>(1,3,true),null);这也是可以的 List<Student> students = pageResult.getRecords(); System.out.println(students); System.out.println("总页数: " + pageResult.getPages()); System.out.println("总记录数:"+ pageResult.getTotal()); System.out.println("当前页码:" + pageResult.getCurrent()); System.out.println("每页大小:" + pageResult.getSize()); } }
本文来自博客园,作者:墨镜一戴谁也不爱,转载请注明原文链接:https://www.cnblogs.com/hnuzmh/p/16196495.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)