MyBatis Plus 的使用之入门

MyBatis Plus 的使用之入门,第1张

概述本博客介绍了 MyBatis Plus 的概念,Spring Boot 的整合,以及 MyBatis Plus 常用 CURD 用法。 一. 什么是 MyBatis Plus

MyBatis Plus 是国内人员开发的 MyBatis 增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。它类似于JPA,对通用的 CRUD 方法进行封装,在进行简单的单表 *** 作时,我们不需要再写xml,而是直接调用这些方法即可,使开发更加简单顺畅。

MyBatis Plus 的核心功能有:支持通用的 CRUD、代码生成器 与 条件构造器。

通用 CRUD:定义好 Mapper 接口后,只需要继承 BaseMapper<T>接口即可获得通用的增删改查功能,无需编写任何接口方法与配置文件.

条件构造器:通过 EntityWrapper<T> (实体包装类),可以用于拼接 sql 语句,并且支持排序、分组查询等复杂的 sql。

代码生成器:支持策略配置与全局配置,比 MyBatis 的代码生成更好用。

二. Spring Boot 整合 MyBatis Plus

正如官方所说,MyBatis Plus 在 MyBatis 的基础上只做增强不做改变,因此其与 Spring Boot 的整合亦非常简单,只需把 MyBatis 的依赖换成 MyBatis Plus 的依赖即可。

1.在pom.xml中加入对应依赖

<!-- MyBatis Plus 依赖 -->  <dependency>      <groupID>com.baomIDou</groupID>      <artifactID>mybatis-plus</artifactID>      <version>2.3</version>  </dependency>

2.在 application.propertIEs 添加配置,打开驼峰到下划线的映射

mybatis-plus.configuration.map-underscore-to-camel-case = true

3.创建用户表

#创建用户表CREATE table user (    ID BIGINT(20) PRIMARY KEY NOT NulL COMMENT '主键',    name VARCHAR(30) DEFAulT NulL COMMENT '姓名',    age INT(11) DEFAulT NulL COMMENT '年龄',    address_ID BIGINT(20) DEFAulT NulL COMMENT '家庭住址ID',    create_time DATETIME DEFAulT NulL COMMENT '创建时间')  ENGINE=INNODB CHARSET=UTF8;

4.新建与 user 表映射的实体类

// @Data 是 Lombok 的注解,是一种 Java 实用工具,会为我们自动生成 set 和 get 方法@Datapublic class User {    private Long ID;    private String name;    private Integer age;    private Long addressID;    private Date createTime;}

5.dao 层中创建 mapper 接口,继承 MyBatis Plus 的 BaseMapper

public interface UserMapper extends BaseMapper<User> {}

6.启动类添加 @MapperScan 注解,配置需要扫描的 dao 层接口

@MapperScan("org.demo.dao")@SpringBootApplicationpublic class MyBatisPlusDemoApplication {    public static voID main(String[] args) {        SpringApplication.run(MyBatisPlusDemoApplication.class, args);    }}

7.编写测试类

@RunWith(springrunner.class)@SpringBoottestpublic class MyBatisPlusDemoApplicationTests {    @Resource    private UserMapper userMapper;        @Test    public voID select(){        List<User> users = userMapper.selectList(null);        users.forEach(System.out::println);    }}
三. MyBatis Plus 的常用 CURD 1.insert *** 作
	User user = new User();    user.setAge(3);    user.setAddressID(10L);    user.setCreateTime(new Date());    userMapper.insert(user);    System.out.println("用户ID为:" + user.ID);
2.update *** 作
	User user = new User();	user.setID(1L);    user.setAge(13);	//根据 ID 进行更新,没有传值的属性就不会更新    userMapper.updateByID(user);
3.select *** 作

(1). 根据 ID 查询:

	User user = userMapper.selectByID(1L);

(2). 根据条件查询单条:

	User user = new User();	user.setID(1L);	//若是数据库中符合传入的条件的记录有多条,那就不能用这个方法,会报错	User user = userMapper.selectOne(user);

(3). 根据条件查询多条:

	Map<String,Object> columnMap = new HashMap<>();	// 表中的列名	columnMap.put("age",13);	List<User> users = userMapper.selectByMap(columnMap);

(4). 通过ID批量查询:

	List<Long> IDList = new ArrayList<>();	IDList.add(1L);	IDList.add(2L);	IDList.add(3L);	List<User> users = userMapper.selectBatchIDs(IDList);
4.delete *** 作

(1). 根据 ID 删除:

	userMapper.deleteByID(1L);

(2). 根据条件删除:

	Map<String,Object> columnMap = new HashMap<>();	columnMap.put("age", 18);	userMapper.deleteByMap(columnMap);

(3). 根据ID批量删除:

 	List<Integer> IDList = new ArrayList<>(); 	IDList.add(1); 	IDList.add(2); 	userMapper.deleteBatchIDs(IDList);
四. 条件构造器

1.allEq

全部 eq (或个别 isNull)

allEq({ID:1,name:"老王",age:null})  --->  ID = 1 and name = '老王' and age is nullallEq({ID:1,age:null}, false)  --->  ID = 1 and name = '老王'

2.eq

等于 =

eq("name", "老王")  --->  name = '老王'

3.ne

不等于 <>

ne("name", "老王")  --->  name <> '老王'

4.gt

大于 >

gt("age", 18)  --->  age > 18

5.ge

大于等于 >=

ge("age", 18) ---> age >= 18

6.lt
小于 <

lt("age", 18) ---> age < 18

7.le
小于等于 <=

le("age", 18) ---> age <= 18

8.between

BETWEEN 值1 AND 值2

between("age", 18, 30) ---> age between 18 and 30

9.notBetween

NOT BETWEEN 值1 AND 值2

notBetween("age", 30) ---> age not between 18 and 30

10.like

liKE ‘%值%’

like("name", "王") ---> name like '%王%'

10.notlike

NOT liKE ‘%值%’

notlike("name", "王") ---> name not like '%王%'

11.likeleft

liKE ‘%值’

likeleft("name", "王") ---> name like '%王'

12.likeRight

liKE ‘值%’

likeRight("name", "王") ---> name like '王%'

13.isNull

字段 IS NulL

isNull("name") ---> name is null

14.isNotNull

字段 IS NOT NulL

isNotNull("name") ---> name is not null

15.in

字段 IN (value.get(0),value.get(1),…)

in("age",{1,2,3}) ---> age in (1,3)

字段 IN (v0,v1, 1, 2, 3) ---> age in (1,3)

16.notin

字段 NOT IN (value.get(0),…)

notin("age",3}) ---> age not in (1,3)

字段 NOT IN (v0, 3) ---> age not in (1,3)

17.insql

字段 IN ( SQL语句 )

insql("age", "1,2,3,4,5,6") ---> age in (1,3,4,5,6)insql("ID", "select ID from table where ID < 3") ---> ID in (select ID from table where ID < 3)

18.notinsql

字段 NOT IN ( SQL语句 )

notinsql("age",6") ---> age not in (1,6)notinsql("ID", "select ID from table where ID < 3") ---> ID not in (select ID from table where ID < 3)

19.groupBy

分组:GROUP BY 字段,…

groupBy("ID", "name") ---> group by ID,name

20.orderByAsc

排序:ORDER BY 字段,… ASC

orderByAsc("ID", "name") ---> order by ID ASC,name ASC

21.orderByDesc

排序:ORDER BY 字段,… DESC

orderByDesc("ID", "name") ---> order by ID DESC,name DESC

22.orderBy

排序:ORDER BY 字段,…

orderBy(true, true, "ID",name ASC

23.having

HAVING ( SQL语句 )

having("sum(age) > 10") ---> having sum(age) > 10having("sum(age) > {0}", 11) ---> having sum(age) > 11

24.or

拼接 OR

eq("ID",1).or().eq("name","老王") ---> ID = 1 or name = '老王'

OR 嵌套

or(i -> i.eq("name", "李白").ne("status", "活着")) ---> or (name = '李白' and status <> '活着')

25.and

AND 嵌套

and(i -> i.eq("name", "活着")) ---> and (name = '李白' and status <> '活着')

26.last

无视优化规则直接拼接到 sql 的最后

注意事项:只能调用一次,多次调用以最后一次为准 有sql注入的风险,谨慎使用

last("limit 1")

27.exists

拼接 EXISTS ( SQL语句 )

exists("select ID from table where age = 1") ---> exists (select ID from table where age = 1)

28.notExists

拼接 NOT EXISTS ( SQL语句 )

notExists("select ID from table where age = 1") ---> not exists (select ID from table where age = 1)

29.自定义sql

Service.java

MysqLMapper.getAllList(Wrappers.<MysqLData>lambdaquery().eq(MysqLData::getGroup, 1));

方案一 注解方式 Mapper.java

@Select("select * from MysqL_data ${ew.customsqlSegment}")List<MysqLData> getAllList(@Param(Constants.WRAPPER) Wrapper wrapper);

方案二 XML形式 Mapper.xml

<select ID="getAllList" resultType="MysqLData">	SELECT * FROM MysqL_data ${ew.customsqlSegment}</select>
总结

以上是内存溢出为你收集整理的MyBatis Plus 的使用之入门全部内容,希望文章能够帮你解决MyBatis Plus 的使用之入门所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1210639.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存