百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

三分钟学会使用Mybatis-Plus——笔记

yuyutoo 2024-10-12 00:03 10 浏览 0 评论

简介

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);

}

详细文档:CRUD 接口 | MyBatis-Plus

条件构造器

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());

}

相关推荐

Mysql和Oracle实现序列自增(oracle创建序列的sql)

Mysql和Oracle实现序列自增/*ORACLE设置自增序列oracle本身不支持如mysql的AUTO_INCREMENT自增方式,我们可以用序列加触发器的形式实现,假如有一个表T_WORKM...

关于Oracle数据库12c 新特性总结(oracle数据库19c与12c)

概述今天主要简单介绍一下Oracle12c的一些新特性,仅供参考。参考:http://docs.oracle.com/database/121/NEWFT/chapter12102.htm#NEWFT...

MySQL CREATE TABLE 简单设计模板交流

推荐用MySQL8.0(2018/4/19发布,开发者说同比5.7快2倍)或同类型以上版本....

mysql学习9:创建数据库(mysql5.5创建数据库)

前言:我也是在学习过程中,不对的地方请谅解showdatabases;#查看数据库表createdatabasename...

MySQL面试题-CREATE TABLE AS 与CREATE TABLE LIKE的区别

执行"CREATETABLE新表ASSELECT*FROM原表;"后,新表与原表的字段一致,但主键、索引不会复制到新表,会把原表的表记录复制到新表。...

Nike Dunk High Volt 和 Bright Spruce 预计将于 12 月推出

在街上看到的PandaDunk的超载可能让一些球鞋迷们望而却步,但Dunk的浪潮仍然强劲,看不到尽头。我们看到的很多版本都是为女性和儿童制作的,这种新配色为后者引入了一种令人耳目一新的新选择,而...

美国多功能舰载雷达及美国海军舰载多功能雷达系统技术介绍

多功能雷达AN/SPY-1的特性和技术能力,该雷达已经在美国海军服役了30多年,其修改-AN/SPY-1A、AN/SPY-1B(V)、AN/SPY-1D、AN/SPY-1D(V),以及雷神...

汽车音响怎么玩,安装技术知识(汽车音响怎么玩,安装技术知识视频)

全面分析汽车音响使用或安装技术常识一:主机是大多数人最熟习的音响器材,有关主机的各种性能及规格,也是耳熟能详的事,以下是一些在使用或安装时,比较需要注意的事项:LOUDNESS:几年前的主机,此按...

【推荐】ProAc Response系列扬声器逐个看

有考牌(公认好声音)扬声器之称ProAcTablette小音箱,相信不少音响发烧友都曾经,或者现在依然持有,正当大家逐渐掌握Tablette的摆位设定与器材配搭之后,下一步就会考虑升级至表现更全...

#本站首晒# 漂洋过海来看你 — BLACK&amp;DECKER 百得 BDH2000L无绳吸尘器 开箱

作者:初吻给了烟sco混迹张大妈时日不短了,手没少剁。家里有了汪星人,吸尘器使用频率相当高,偶尔零星打扫用卧式的实在麻烦(汪星人:你这分明是找借口,我掉毛是满屋子都有,铲屎君都是用卧式满屋子吸的,你...

专题|一个品牌一件产品(英国篇)之Quested(罗杰之声)

Quested(罗杰之声)代表产品:Q212FS品牌介绍Quested(罗杰之声)是录音监听领域的传奇品牌,由英国录音师RogerQuested于1985年创立。在成立Quested之前,Roger...

常用半导体中英对照表(建议收藏)(半导体英文术语)

作为一个源自国外的技术,半导体产业涉及许多英文术语。加之从业者很多都有海外经历或习惯于用英文表达相关技术和工艺节点,这就导致许多英文术语翻译成中文后,仍有不少人照应不上或不知如何翻译。为此,我们整理了...

Fyne Audio F502SP 2.5音路低音反射式落地音箱评测

FyneAudio的F500系列,有新成员了!不过,新成员不是新的款式,却是根据原有款式提出特别版。特别版产品在原有型号后标注了SP字样,意思是SpecialProduction。Fyne一共推出...

有哪些免费的内存数据库(In-Memory Database)

以下是一些常见的免费的内存数据库:1.Redis:Redis是一个开源的内存数据库,它支持多种数据结构,如字符串、哈希表、列表、集合和有序集合。Redis提供了快速的读写操作,并且支持持久化数据到磁...

RazorSQL Mac版(SQL数据库查询工具)

RazorSQLMac特别版是一款看似简单实则功能非常出色的SQL数据库查询、编辑、浏览和管理工具。RazorSQLformac特别版可以帮你管理多个数据库,支持主流的30多种数据库,包括Ca...

取消回复欢迎 发表评论: