三分钟学会使用Mybatis-Plus——笔记
bigegpt 2024-10-05 13:34 3 浏览
简介
MyBatis-plus是mybatis的增强工具,在MyBatis 上只做增强,不做改变,引入他不会对现有工程产生影响,只需简单配置快速实现CURD操作,从而节省大量时间。代码生成、自动分页、逻辑删除、自动、填充等功能一应俱全。
安装
首先创建一个springboot项目,导入Mybatis-plus相关依赖:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
由于Mybatis-plus是包含Mybatis 依赖的所以导入Mybatis-plus后就不用导入Mybatis了
配置
在springboot的yml文件中可以配置实体类别名和mapper文件路径:
mybatis-plus:
mapper-locations: classpath*:/mapper/**/*.xml
type-aliases-package: com.xxz.pojo
mapperlocations 自动配置好的,默认值是classpath*:/mapper/**/*.xml 意为任意包路径下所有的mapper包下的xml文件
也可以使用Mybatis中的方法进行配置,因为Mybatis-plus是只做增强不做改变。
实体类常用注解
@TableName("dept") 对应数据库的表明
@TableField("deptno") 对应数据库的字段名
@TableField(exist = false) 是否为数据库表字段
详细文档:注解 | MyBatis-Plus
@AllArgsConstructor
@NoArgsConstructor
@Data
@TableName("dept")//用于数据库表明和实体类名不一致情况
public class Dept implements Serializable {
/*@TableField(exist = false)
private String aaa;*/
@TableField("deptno")//用于数据库字段名和实体类属性不一致情况
private Integer deptno;
private String dname;
private String loc;
}
使用
mapper类需要实现BaseMapper<T>接口,传入实体类的泛型
public interface DeptMapper extends BaseMapper<Dept> {
}
service接口需要继承Iservice<T>类,传入实体类的泛型
public interface DeptService extends IService<Dept> {
}
service实现类需要继承ServiceImpl<M,T>类,传入mapper类,和实体类的泛型
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {
}
CRUD接口
save方法:
// 插入一条记录(选择字段,策略插入)
boolean save(T entity); entity实体对象
// 插入(批量)
boolean saveBatch(Collection<T> entityList); entityList实体对象集合
// 插入(批量)
boolean saveBatch(Collection<T> entityList, int batchSize); batchSize插入批次数量
// 增加
@Test
public void testAdd(){
boolean save = deptService.save(new Dept(null, "aaa", "bbb"));
System.out.println(save);
}
list方法:
// 查询所有
List<T> list();
// 查询列表
List<T> list(Wrapper<T> queryWrapper);queryWrapper条件构造
// 查询集合
@Test
public void testQueryWrapper(){
// 部门号》=20
// QueryWrapper 作用就是在原本的SQL语句后面拼接where条件
// selec * from where delete from dept where update dept set ... where ....
QueryWrapper<Dept> queryWrapper=new QueryWrapper<>();
//queryWrapper.ge("deptno", 20).eq("dname", "ACCOUNTING").likeRight("dname", "A");
//queryWrapper.likeRight("dname", "A");
List<Dept> list = deptService.list(queryWrapper);
for (Dept dept : list) {
System.out.println(dept);
}
}
// 查询单个
@Test
public void testQueryWrapper2(){
QueryWrapper<Dept> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("deptno", 20);
Dept dept = deptService.getOne(queryWrapper);
System.out.println(dept);
}
update方法:
// 根据 UpdateWrapper 条件
boolean update(Wrapper<T> updateWrapper);
// 根据 whereWrapper 条件,更新记录
boolean update(T updateEntity, Wrapper<T> whereWrapper);
// 根据 ID 选择修改
boolean updateById(T entity);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList, int batchSize);
// 修改
@Test
public void testUpdate(){
// 要更新的数据
Dept dept =new Dept();
dept.setDname("xxx");
dept.setLoc("yyy");
// 更新的条件
QueryWrapper<Dept> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("deptno", 41);
boolean update = deptService.update(dept, queryWrapper);
System.out.println(update);
}
remove方法:
// 根据 entity 条件,删除记录
boolean remove(Wrapper<T> queryWrapper);
// 删除
@Test
public void testRemove(){
QueryWrapper<Dept> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("deptno", 41);
boolean remove = deptService.remove(queryWrapper);
System.out.println(remove);
}
条件构造器
AbstractWrapper
说明: QueryWrapper(LambdaQueryWrapper) 和 UpdateWrapper(LambdaUpdateWrapper) 的父类
用于生成 sql 的 where 条件, entity 属性也用于生成 sql 的 where 条件
注意: entity 生成的 where 条件与 使用各个 api 生成的 where 条件没有任何关联行为
方法 :
- eq:等于 = 例: eq("name", "老王")--->name = '老王'
- ne:不等于<> 例: ne("name", "老王")--->name <> '老王'
- gt:大于> 例: gt("age", 18)--->age > 18
- ge:大于等于>= 例: ge("age", 18)--->age >= 18
- lt:小于< 例:lt("age", 18)--->age < 18
- le:小于等于<= 例:le("age", 18)--->age <= 18
- between:BETWEEN 值1 AND 值2 例: between("age", 18, 30)--->age between 18 and 30
- notBetween:NOT BETWEEN 值1 AND 值2 例: notBetween("age", 18, 30)--->age not between 18 and 30
- like:LIKE '%值%' 例: like("name", "王")--->name like '%王%'
- notLike:NOT LIKE '%值%' 例: notLike("name", "王")--->name not like '%王%'
- likeLeft:LIKE '%值' 例: likeLeft("name", "王")--->name like '%王'
- likeRight:LIKE '值%' 例: likeRight("name", "王")--->name like '王%'
- isNull:字段 IS NULL 例: isNull("name")--->name is null
- isNotNull:字段 IS NOT NULL 例: isNotNull("name")--->name is not null
- in:字段 IN (value.get(0), value.get(1), ...) 例: in("age",{1,2,3})--->age in (1,2,3)
- notIn:字段 NOT IN (value.get(0), value.get(1), ...) 例: notIn("age",{1,2,3})--->age not in (1,2,3)
- inSql:字段 IN ( sql语句 ) 例: inSql("age", "1,2,3,4,5,6")--->age in (1,2,3,4,5,6) 例: inSql("id", "select id from table where id < 3")--->id in (select id from table where id < 3)
- notSql:字段 NOT IN ( sql语句 ) 例: notInSql("age", "1,2,3,4,5,6")--->age not in (1,2,3,4,5,6) 例: notInSql("id", "select id from table where id < 3")--->id not in (select id from table where id < 3)
- groupBy:分组:GROUP BY 字段, ... 例: groupBy("id", "name")--->group by id,name
- orderByAse:排序:ORDER BY 字段, ... ASC 例: orderByAsc("id", "name")--->order by id ASC,name ASC
- orderByDesc:排序:ORDER BY 字段, ... DESC 例: orderByDesc("id", "name")--->order by id DESC,name DESC
- orderBy:排序:ORDER BY 字段, ... 例: orderBy(true, true, "id", "name")--->order by id ASC,name ASC
- having:HAVING ( sql语句 ) 例: having("sum(age) > 10")--->having sum(age) > 10 例: having("sum(age) > {0}", 11)--->having sum(age) > 11
or:
拼接 OR
例: eq("id",1).or().eq("name","老王")--->id = 1 or name = '老王'
注意事项: 主动调用or表示紧接着下一个方法不是用and连接!(不调用or则默认为使用and连接)
OR 嵌套
例: or(i -> i.eq("name", "李白").ne("status", "活着"))--->or (name = '李白' and status <> '活着')
and:
AND 嵌套
例: and(i -> i.eq("name", "李白").ne("status", "活着"))--->and (name = '李白' and status <> '活着')
nested:
正常嵌套 不带 AND 或者 OR
例: nested(i -> i.eq("name", "李白").ne("status", "活着"))--->(name = '李白' and status <> '活着')
apply:
拼接 sql
注意事项:
该方法可用于数据库函数 动态入参的params对应前面applySql内部的{index}部分.这样是不会有sql注入风险的,反之会有!
例: apply("id = 1")--->id = 1
例: apply("date_format(dateColumn,'%Y-%m-%d') = '2008-08-08'")--->date_format(dateColumn,'%Y-%m-%d') = '2008-08-08'")
例: apply("date_format(dateColumn,'%Y-%m-%d') = {0}", "2008-08-08")--->date_format(dateColumn,'%Y-%m-%d') = '2008-08-08'")
last:
无视优化规则直接拼接到 sql 的最后
注意事项:
只能调用一次,多次调用以最后一次为准 有sql注入的风险,请谨慎使用
例: last("limit 1")
exists:
拼接 EXISTS ( sql语句 )
例: exists("select id from table where age = 1")--->exists (select id from table where age = 1)
notExists:
拼接 NOT EXISTS ( sql语句 )
例: notExists("select id from table where age = 1")--->not exists (select id from table where age = 1)
select:
设置查询字段
select(String... sqlSelect)
select(Predicate<TableFieldInfo> predicate)
select(Class<T> entityClass, Predicate<TableFieldInfo> predicate)
说明:
以上方法分为两类.
第二类方法为:过滤查询字段(主键除外),入参不包含 class 的调用前需要wrapper内的entity属性有值! 这两类方法重复调用以最后一次为准
例: select("id", "name", "age")
例: select(i -> i.getProperty().startsWith("test"))
UpdateWrapper :
set:
SQL SET 字段
例: set("name", "老李头")
例: set("name", "")--->数据库字段值变为空字符串
例: set("name", null)--->数据库字段值变为null
setSql:
设置 SET 部分 SQL
例: setSql("name = '老李头'")
分页
配置分页插件
@Configuration
@MapperScan("scan.your.mapper.package")
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> configuration.setUseDeprecatedExecutor(false);
}
}
测试分页插件
@Test
public void testPage(){
// 当前页 页大小
QueryWrapper<Dept> queryWrapper=new QueryWrapper<>();
//queryWrapper.likeRight("dname", "A");
Page<Dept> page = deptService.page(new Page<>(1, 2), queryWrapper);
// 当前页数据 总页数 总记录数 当前页 页大小 ... ..
List<Dept> list = page.getRecords();
list.forEach(System.out::println);
System.out.println("总页数:"+page.getPages());
System.out.println("总记录数:"+page.getTotal());
System.out.println("当前页:"+page.getCurrent());
System.out.println("页大小:"+page.getSize());
}
相关推荐
- C#.NET Autofac 详解(c# autoit)
-
简介Autofac是一个成熟的、功能丰富的.NET依赖注入(DI)容器。相比于内置容器,它额外提供:模块化注册、装饰器(Decorator)、拦截器(Interceptor)、强o的属性/方法注...
- webapi 全流程(webapi怎么部署)
-
C#中的WebAPIMinimalApi没有控制器,普通api有控制器,MinimalApi是直达型,精简了很多中间代码,广泛适用于微服务架构MinimalApi一切都在组控制台应用程序类【Progr...
- .NET外挂系列:3. 了解 harmony 中灵活的纯手工注入方式
-
一:背景1.讲故事上一篇我们讲到了注解特性,harmony在内部提供了20个HarmonyPatch重载方法尽可能的让大家满足业务开发,那时候我也说了,特性虽然简单粗暴,但只能解决95%...
- C# 使用SemanticKernel调用本地大模型deepseek
-
一、先使用ollama部署好deepseek大模型。具体部署请看前面的头条使用ollama进行本地化部署deepseek大模型二、创建一个空的控制台dotnetnewconsole//添加依赖...
- C#.NET 中间件详解(.net core中间件use和run)
-
简介中间件(Middleware)是ASP.NETCore的核心组件,用于处理HTTP请求和响应的管道机制。它是基于管道模型的轻量级、模块化设计,允许开发者在请求处理过程中插入自定义逻辑。...
- IoC 自动注入:让依赖注册不再重复劳动
-
在ASP.NETCore中,IoC(控制反转)功能通过依赖注入(DI)实现。ASP.NETCore有一个内置的依赖注入容器,可以自动完成依赖注入。我们可以结合反射、特性或程序集扫描来实现自动...
- C#.NET 依赖注入详解(c#依赖注入的三种方式)
-
简介在C#.NET中,依赖注入(DependencyInjection,简称DI)是一种设计模式,用于实现控制反转(InversionofControl,IoC),以降低代码耦合、提高可...
- C#从零开始实现一个特性的自动注入功能
-
在现代软件开发中,依赖注入(DependencyInjection,DI)是实现松耦合、模块化和可测试代码的一个重要实践。C#提供了优秀的DI容器,如ASP.NETCore中自带的Micr...
- C#.NET 仓储模式详解(c#仓库货物管理系统)
-
简介仓储模式(RepositoryPattern)是一种数据访问抽象模式,它在领域模型和数据访问层之间创建了一个隔离层,使得领域模型无需直接与数据访问逻辑交互。仓储模式的核心思想是将数据访问逻辑封装...
- C#.NET 泛型详解(c# 泛型 滥用)
-
简介泛型(Generics)是指在类型或方法定义时使用类型参数,以实现类型安全、可重用和高性能的数据结构与算法为什么需要泛型类型安全防止“装箱/拆箱”带来的性能损耗,并在编译时检测类型错误。可重用同一...
- 数据分析-相关性分析(相关性 分析)
-
相关性分析是一种统计方法,用于衡量两个或多个变量之间的关系强度和方向。它通过计算相关系数来量化变量间的线性关系,从而帮助理解变量之间的相互影响。相关性分析常用于数据探索和假设检验,是数据分析和统计建模...
- geom_smooth()函数-R语言ggplot2快速入门18
-
在每节,先运行以下这几行程序。library(ggplot2)library(ggpubr)library(ggtext)#用于个性化图表library(dplyr)#用于数据处理p...
- 规范申报易错要素解析(规范申报易错要素解析)
-
为什么要规范申报?规范申报是以满足海关监管、征税、统计等工作为目的,纳税义务人及其代理人依法向海关如实申报的行为,也是海关审接单环节依法监管的重要工作。企业申报的内容须符合《中华人民共和国海关进出口货...
- 「Eurora」海关编码归类 全球海关编码查询 关务服务
-
海关编码是什么? 海关编码即HS编码,为编码协调制度的简称。 其全称为《商品名称及编码协调制度的国际公约》(InternationalConventionforHarmonizedCo...
- 9月1日起,河南省税务部门对豆制品加工业试行新政7类豆制品均适用投入产出法
-
全媒体记者杨晓川报道9月2日,记者从税务部门获悉,为减轻纳税人税收负担,完善农产品增值税进项税额抵扣机制,根据相关规定,结合我省实际情况,经广泛调查研究和征求意见,从9月1日起,我省税务部门对豆制品...
- 一周热门
- 最近发表
- 标签列表
-
- mybatiscollection (79)
- mqtt服务器 (88)
- keyerror (78)
- c#map (65)
- xftp6 (83)
- bt搜索 (75)
- c#var (76)
- xcode-select (66)
- mysql授权 (74)
- 下载测试 (70)
- linuxlink (65)
- pythonwget (67)
- androidinclude (65)
- libcrypto.so (74)
- linux安装minio (74)
- ubuntuunzip (67)
- vscode使用技巧 (83)
- secure-file-priv (67)
- vue阻止冒泡 (67)
- jquery跨域 (68)
- php写入文件 (73)
- kafkatools (66)
- mysql导出数据库 (66)
- jquery鼠标移入移出 (71)
- 取小数点后两位的函数 (73)