Mybatis-plus学习笔记
在Springboot中使用mp并测试
在pom文件中引入如下依赖:(mp依赖和mysq依赖)
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
基础配置:
在application.yml中配置基本数据连接信息:
# DataSource Config
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mp?useSSL=false&serverTimezone=GMT%2B8
username: root
password: root
# Logger Config
logging:
level:
com.neo: warn
com.neo.mapper: trace
pattern:
console: '%p%m%n'
调入测试数据库脚本:
/*
Navicat Premium Data Transfer
Source Server : 本地数据库
Source Server Type : MySQL
Source Server Version : 50726
Source Host : localhost:3306
Source Schema : mp
Target Server Type : MySQL
Target Server Version : 50726
File Encoding : 65001
Date: 02/02/2020 21:11:32
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL COMMENT '主键',
`name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',
`age` int(11) NULL DEFAULT NULL COMMENT '年龄',
`email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '邮箱',
`manager_id` bigint(20) NULL DEFAULT NULL COMMENT '直属上级id',
`create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`) USING BTREE,
INDEX `manager_fk`(`manager_id`) USING BTREE,
CONSTRAINT `manager_fk` FOREIGN KEY (`manager_id`) REFERENCES `user` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1087982257332887553, '大boss', 40, 'boss@baomidou.com', NULL, '2019-01-11 14:20:20');
INSERT INTO `user` VALUES (1088248166370832385, '王天风', 25, 'wtf@baomidou.com', 1087982257332887553, '2019-02-05 11:12:22');
INSERT INTO `user` VALUES (1088250446457389058, '李艺伟', 28, 'lyw@baomidou.com', 1088248166370832385, '2019-02-14 08:31:16');
INSERT INTO `user` VALUES (1094590409767661570, '张雨琪', 31, 'zjq@baomidou.com', 1088248166370832385, '2019-01-14 09:15:15');
INSERT INTO `user` VALUES (1094592041087729666, '刘红雨', 32, 'lhm@baomidou.com', 1088248166370832385, '2019-01-14 09:48:16');
SET FOREIGN_KEY_CHECKS = 1;
在Springboot的测试包中创建测试类,测试配置是否成功:
package com.neo;
import com.neo.mapper.UserMapper;
import com.neo.model.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.sql.SQLOutput;
import java.util.List;
/**
* @author Alex
* @create 2020-02-02 20:37
**/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SimpleTest {
@Autowired
private UserMapper userMapper;
@Test
public void select(){
List<User> users = userMapper.selectList(null);
Assert.assertEquals(5,users.size());
users.forEach(System.out::println);
}
}
测试结果:
User(id=1087982257332887553, name=大boss, age=40, email=boss@baomidou.com, managerId=null, createTime=2019-01-11T14:20:20)
User(id=1088248166370832385, name=王天风, age=25, email=wtf@baomidou.com, managerId=1087982257332887553, createTime=2019-02-05T11:12:22)
User(id=1088250446457389058, name=李艺伟, age=28, email=lyw@baomidou.com, managerId=1088248166370832385, createTime=2019-02-14T08:31:16)
User(id=1094590409767661570, name=张雨琪, age=31, email=zjq@baomidou.com, managerId=1088248166370832385, createTime=2019-01-14T09:15:15)
User(id=1094592041087729666, name=刘红雨, age=32, email=lhm@baomidou.com, managerId=1088248166370832385, createTime=2019-01-14T09:48:16)
通用mapper
新增(Create)
◆新增方法
UserMapper代码:
package com.neo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.neo.model.User;
import org.apache.ibatis.annotations.Mapper;
//要使用mp,就要集成BaseMapper
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
在测试方法中调用userMapper中的insert方法:
@Test
public void insert(){
User user = new User();
user.setName("黄小明");
user.setAge(20);
user.setManagerId(1088248166370832385L);
user.setCreateTime(LocalDateTime.now());
int rows = userMapper.insert(user);
System.out.println("影响记录数:"+rows);
}
测试结果:
DEBUG==> Preparing: INSERT INTO user ( id, name, age, manager_id, create_time ) VALUES ( ?, ?, ?, ?, ? )
DEBUG==> Parameters: 1223961279246393345(Long), 黄小明(String), 20(Integer), 1088248166370832385(Long), 2020-02-02T21:28:03.621(LocalDateTime)
DEBUG<== Updates: 1
影响记录数:1
◆常用注解
@TabName注解
当修改数据库表明却不想修改实体类型时,可以通过@TabName("数据库表名")来指定表名,否则会运行报错
@Data
@TableName("mp_user")
public class User {
//主键
private Long id;
//姓名
private String name;
//年龄
private Integer age;
//邮箱
private String email;
//直属上级
private Long managerId;
//创建时间
private LocalDateTime createTime;
}
@TabId注解
当实例中主键与数据库中的主键名称不一致时(例如实例中为驼峰命名,数据库表中为下划线命名),可使用该注解
@TableField注解
当实例中的字段与数据库中的字段不同时,就可以使用该注解映射,如下例:
@TableField("name")
private String realName;
◆排除非表字段的三种方式
第一种方法:在声明类属性时使用 transient 关键字声明
第二种方法:如上方法可能无法序列化该字段,故可以在声明类属性时:使用 static 关键字声明为静态变量(注意,用static 声明的静态变量lombok不会为其添加set和get方法)
第三种方法:使用@TableField(exist = true)注解注解 其中括号中的 exist = true 表示该字段不是数据库表中的字段,无需映射
查询(Retrieve)
◆基本查询方法
通过id查询:selectById()方法
@Test
public void selectById() {
User user = userMapper.selectById(1094590409767661570L);
System.out.println(user);
}
批量查询:selectBatchIds()
@Test
public void selectByIds() {
List<Long> idsList = Arrays.asList(1094592041087729666L, 1223961279246393345L, 1088250446457389058L);
List<User> users = userMapper.selectBatchIds(idsList);
users.forEach(System.out::println);
}
通过map查询:
@Test
public void selectByMap() {
Map<String,Object> columnMap = new HashMap<>();
columnMap.put("name","王天风");
columnMap.put("age",25);
//通过此map会执行类似 where name="王天风" and age=25 的sql
List<User> userList = userMapper.selectByMap(columnMap);
userList.forEach(System.out::println);
}
注意:此map中的键名为数据表中列名,并非实体类中的属性名
◆以条件构造器为参数的查询方法
/* 查询要求:
1、名字中包含雨并且年龄小于40
name like '%雨%' and age<40
*/
@Test
public void selectByWrapper() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//等同于
//QueryWrapper<User> query = Wrappers.<User>query();
queryWrapper.like("name","雨").lt("age",40);
//注意:此处的键名依旧为数据库中的列名
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
/*
2、名字中包含雨年并且龄大于等于20且小于等于40并且email不为空
name like '%雨%' and age between 20 and 40 and email is not null
*/
@Test
public void selectByWrapper2() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//等同于
//QueryWrapper<User> query = Wrappers.<User>query();
queryWrapper.like("name","雨").between("age",20,40).isNotNull("email");
//注意:此处的键名依旧为数据库中的列名
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
/*
3、名字为王姓或者年龄大于等于25,按照年龄降序排列,年龄相同按照id升序排列
name like '王%' or age>=25 order by age desc,id asc
*/
@Test
public void selectByWrapper3() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//等同于
//QueryWrapper<User> query = Wrappers.<User>query();
queryWrapper.likeRight("name","王").or()
.ge("age",25).orderByDesc("age").orderByAsc("id");
//注意:此处的键名依旧为数据库中的列名
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
/*
4、创建日期为2019年2月14日并且直属上级为名字为王姓
date_format(create_time,'%Y-%m-%d')='2019-02-14' and manager_id in (select id from user where name like '王%')
*/
@Test
public void selectByWrapper4() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//等同于
//QueryWrapper<User> query = Wrappers.<User>query();
queryWrapper.apply("date_format(create_time,'%Y-%m-%d')={0}","2019-02-14")
.inSql("manager_id","select id from user where name like '王%'");
//注意:此处的键名依旧为数据库中的列名
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
//注意:以上方法查询为推荐查询,不建议写如下方式查询:会导致sql注入风险
//queryWrapper.apply("date_format(create_time,'%Y-%m-%d')="2019-02-14")
/*
5、名字为王姓并且(年龄小于40或邮箱不为空)
name like '王%' and (age<40 or email is not null)
*/
@Test
public void selectByWrapper5() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//等同于
//QueryWrapper<User> query = Wrappers.<User>query();
queryWrapper.likeRight("name","王").
and(wq->wq.lt("age",40)
.or().isNotNull("email"));
//注意:此处的键名依旧为数据库中的列名
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
/*
6、名字为王姓或者(年龄小于40并且年龄大于20并且邮箱不为空)
name like '王%' or (age<40 and age>20 and email is not null)
*/
@Test
public void selectByWrapper6() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//等同于
//QueryWrapper<User> query = Wrappers.<User>query();
queryWrapper.likeRight("name","王")
.or(wq->wq.lt("age",40).gt("age",20).isNotNull("email"));
//注意:此处的键名依旧为数据库中的列名
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
/*
7、(年龄小于40或邮箱不为空)并且名字为王姓
(age<40 or email is not null) and name like '王%'
*/
@Test
public void selectByWrapper7() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//等同于
//QueryWrapper<User> query = Wrappers.<User>query();
queryWrapper.nested(wq->wq.lt("age",40).or().
isNotNull("email"))
.likeRight("name","王");
//注意:此处的键名依旧为数据库中的列名
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
/*
8、年龄为30、31、34、35
age in (30、31、34、35)
*/
@Test
public void selectByWrapper8() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//等同于
//QueryWrapper<User> query = Wrappers.<User>query();
queryWrapper.in("age",Arrays.asList(30,31,34,35));
//注意:此处的键名依旧为数据库中的列名
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
◆select中字段不全出现的处理方法
并非每次查询都要查询所有字段,测试可用如下方法查询
/*
10、名字中包含雨并且年龄小于40(需求1加强版)
第一种情况:select id,name
from user
where name like '%雨%' and age<40
*/
@Test
public void selectByWrapperSuper() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select("id","name").like("name","雨").lt("age",40);
List<User> userList =userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
/*
第二种情况:select id,name,age,email
from user
where name like '%雨%' and age<40
*/
@Test
public void selectByWrapperSuper2() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name","雨").lt("age",40)
.select(User.class,info->!info.getColumn().equals("create_time")
&&!info.getColumn().equals("manager_id"));
List<User> userList =userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
◆条件构造器中condition作用
@Test
public void testCondition() {
String name="王";
String email="";
condition(name,email);
}
public void condition(String name,String email){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
// if(StringUtils.isNotEmpty(name)){
// queryWrapper.like("name",name);
// }
// if(StringUtils.isNotEmpty(email)){
// queryWrapper.like("email",email);
// }
//以上代码过于臃肿,可采用如下代码代替
queryWrapper.like(StringUtils.isNotEmpty(name),"name",name)
.like(StringUtils.isNotEmpty(email),"email",email);
List<User> userList =userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
◆创建条件构造器时传入实体对象
@Test
public void selectByWrapperEntity() {
User whereUser = new User();
whereUser.setName("刘红雨");
whereUser.setAge(32);
QueryWrapper<User> queryWrapper = new QueryWrapper<User>(whereUser);
List<User> userList =userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
◆条件构造器中allEq用法
@Test
public void selectByWrapperAllEq() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
Map<String,Object> params = new HashMap<String,Object>();
params.put("name","王天风");
params.put("age","25");
queryWrapper.allEq(params);
List<User> userList =userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
◆其他以条件构造器为参数的查询方法
@Test
public void selectByWrapperMaps() {
QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
queryWrapper.select("id","name").like("name","雨").lt("age",40);
List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);
maps.forEach(System.out::println);
}
selectMaps:
/*
按照直属上级分组,查询每组的平均年龄、最大年龄、最小年龄。
并且只取年龄总和小于500的组。
select avg(age) avg_age,min(age) min_age,max(age) max_age
from user
group by manager_id
having sum(age) <500
*/
@Test
public void selectByWrapperMaps2() {
QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
queryWrapper.select("avg(age) avg_age","min(age) min_age","max(age) max_age")
.groupBy("manager_id").having("sum(age)<{0}",500);
List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);
maps.forEach(System.out::println);
}
selectObjs:
@Test
public void selectByWrapperObjs() {
QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
queryWrapper.select("id","name").like("name","雨").lt("age",40);
List<Object> userList = userMapper.selectObjs(queryWrapper);
userList.forEach(System.out::println);
}
selectCount :
@Test
public void setUserMapperCount() {
QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
queryWrapper.like("name","雨").lt("age",40);
int count = userMapper.selectCount(queryWrapper);
System.out.println(count);
}
◆Lambda条件构造器
创建lambda条件构造器有两种方法
第一种:
LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
第二种:直接new 一个lambda条件构造器
LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
第三种:
LambdaQueryWrapper<User> LambdaQuery = Wrappers.<User>lambdaQuery();
@Test
public void selectLambda() {
// LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
// LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
LambdaQueryWrapper<User> lambdaQuery = Wrappers.<User>lambdaQuery();
lambdaQuery.like(User::getName,"雨").lt(User::getAge,40);
//where name like '%雨%' and age <40
List<User> userList = userMapper.selectList(lambdaQuery);
userList.forEach(System.out::println);
}
◆使用条件构造器的自定义SQL
(要求版本大于等于3.0.7)
在UserMapper中定于接口方法(采用注解的方式)
@Select("select * from user ${ew.customSqlSegment}")
List<User> selectAll(@Param(Constants.WRAPPER)Wrapper<User> wrapper);
在测试中使用自定义方法:
@Test
public void selectMy() {
// LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
// LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
LambdaQueryWrapper<User> lambdaQuery = Wrappers.<User>lambdaQuery();
lambdaQuery.like(User::getName,"雨").lt(User::getAge,40);
//where name like '%雨%'
List<User> userList = userMapper.selectAll(lambdaQuery);//此处使用自定义接口方法
userList.forEach(System.out::println);
}
如果不想把自定义sql写在接口中,例如写在xml中,还可以采用如下方法:
第一步:在yml配置文件中配置接口对应的xml路径
Mybatis-plus:
mapper-locations: classpath:mp/mapper/*.xml
在配置路径下新建UserMapper.xml文件,同时去除接口中的注解sql
<?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" >
<mapper namespace="com.neo.mapper.UserMapper" >
<select id="selectAll" resultType="com.neo.model.User">
select * from user ${ew.customSqlSegment}
</select>
</mapper>
◆MyBatis分页介绍
mybatis中提供分页方法,但是该分页是逻辑分页,而非物理分页。
◆MP分页插件实现物理分页
新建配置包(com.neo.configuration)并新建配置分页类MybatisPlusConfig:
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
测试(selectPage):
@Test
public void selectPage() {
QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
queryWrapper.ge("age", 26);
Page<User> page = new Page<>(1, 2);
IPage<User> iPage = userMapper.selectPage(page, queryWrapper);
System.out.println("总页数:" + iPage.getPages());
System.out.println("总记录数:" + iPage.getTotal());
List<User> userlist = iPage.getRecords();
userlist.forEach(System.out::println);
}
运行日志:
DEBUG==> Preparing: SELECT COUNT(1) FROM user WHERE age >= ?
DEBUG==> Parameters: 26(Integer)
TRACE<== Columns: COUNT(1)
TRACE<== Row: 7
DEBUG==> Preparing: SELECT id,name,age,email,manager_id,create_time FROM user WHERE age >= ? LIMIT ?,?
DEBUG==> Parameters: 26(Integer), 0(Long), 2(Long)
TRACE<== Columns: id, name, age, email, manager_id, create_time
TRACE<== Row: 1087982257332887553, 大boss, 40, boss@baomidou.com, null, 2019-01-11 14:20:20
TRACE<== Row: 1088250446457389058, 李艺伟, 28, lyw@baomidou.com, 1088248166370832385, 2019-02-14 08:31:16
DEBUG<== Total: 2
总页数:4
总记录数:7
User(id=1087982257332887553, name=大boss, age=40, email=boss@baomidou.com, managerId=null, createTime=2019-01-11T14:20:20)
User(id=1088250446457389058, name=李艺伟, age=28, email=lyw@baomidou.com, managerId=1088248166370832385, createTime=2019-02-14T08:31:16)
测试(selectMapsPage):
@Test
public void selectPage() {
QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
// queryWrapper.ge("age",26);
Page<User> page = new Page<>(1, 2);
// IPage<User> iPage = userMapper.selectPage(page, queryWrapper);
// System.out.println("总页数:"+ iPage.getPages());
// System.out.println("总记录数:"+ iPage.getTotal());
// List<User> userlist = iPage.getRecords();
IPage<Map<String, Object>> iPage = userMapper.selectMapsPage(page, queryWrapper);
System.out.println("总页数:"+ iPage.getPages());
System.out.println("总记录数:"+ iPage.getTotal());
List<Map<String, Object>> userlist = iPage.getRecords();
userlist.forEach(System.out::println);
}
DEBUG==> Preparing: SELECT COUNT(1) FROM user
DEBUG==> Parameters:
TRACE<== Columns: COUNT(1)
TRACE<== Row: 13
DEBUG==> Preparing: SELECT id,name,age,email,manager_id,create_time FROM user LIMIT ?,?
DEBUG==> Parameters: 0(Long), 2(Long)
TRACE<== Columns: id, name, age, email, manager_id, create_time
TRACE<== Row: 1087982257332887553, 大boss, 40, boss@baomidou.com, null, 2019-01-11 14:20:20
TRACE<== Row: 1088248166370832385, 王天风, 25, wtf@baomidou.com, 1087982257332887553, 2019-02-05 11:12:22
DEBUG<== Total: 2
总页数:7
总记录数:13
{createTime=2019-01-11 14:20:20.0, name=大boss, id=1087982257332887553, age=40, email=boss@baomidou.com}
{createTime=2019-02-05 11:12:22.0, name=王天风, id=1088248166370832385, managerId=1087982257332887553, age=25, email=wtf@baomidou.com}
从以上两个例子看以看出每个是执行了两条sql语句,如果只想要查询结果,不想要查询总数,只需要将page的第三个参数变为false,即可:
Page<User> page = new Page<>(1, 2,false);
当我们在做多表联查时,就不能使用如上方式查询了,此时可以在xml文件中自定义sql:
更新(Update)
◆根据id更新
@Test
public void updateById(){
User user= new User();
user.setId(1088248166370832385L);
user.setAge(26);
user.setEmail("wtf2@baomidou.com");
int rows = userMapper.updateById(user);
System.out.println("影响记录数:"+ rows);
}
运行日志:
DEBUG==> Preparing: UPDATE user SET age=?, email=? WHERE id=?
DEBUG==> Parameters: 26(Integer), wtf2@baomidou.com(String), 1088248166370832385(Long)
DEBUG<== Updates: 1
影响记录数:1
◆以条件构造器作为参数的更新方法
@Test
public void updateByWrapper(){
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("name","李艺伟").eq("age",28);
User user = new User();
user.setEmail("lyw2020@baomidou.com");
user.setAge(29);
int rows = userMapper.update(user, updateWrapper);
System.out.println("影响行数:"+rows
);
}
运行日志:
DEBUG==> Preparing: UPDATE user SET age=?, email=? WHERE name = ? AND age = ?
DEBUG==> Parameters: 29(Integer), lyw2020@baomidou.com(String), 李艺伟(String), 28(Integer)
DEBUG<== Updates: 1
影响行数:1
◆条件构造器中set方法使用
(只修改少量字段时):
@Test
public void updateByWrapper(){
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
//通过条件构造器的链式编程设置更新信息
updateWrapper.eq("name","李艺伟").eq("age",29).set("email","liw888@qq.com");
// User user = new User();
int rows = userMapper.update(null, updateWrapper);
System.out.println("影响行数:"+rows
);
}
lambda条件构造器更新:
@Test
public void updateByWrapperLambda(){
LambdaUpdateWrapper<User> lambdaUpdate = Wrappers.<User>lambdaUpdate();
lambdaUpdate.eq(User::getName,"李艺伟").eq(User::getAge,29).set(User::getAge,31);
int rows = userMapper.update(null, lambdaUpdate);
System.out.println("影响行数:"+rows);
}
删除(Delete)
◆根据id删除的方法
@Test
public void deleteById() {
int rows= userMapper.deleteById(1223976086888599553L);
System.out.println("影响行数:"+rows);
}
根据id批量删除:
@Test
public void deleteBatchIds() {
int rows = userMapper.deleteBatchIds(
Arrays.asList(1223973741031141377L,
1223972327026405378L,1223970002606067714L));
System.out.println("影响行数:"+rows);
}
◆其他普通删除方法
@Test
public void deleteByMap() {
Map<String,Object> columnMap= new HashMap<>();
columnMap.put("name","向后");
columnMap.put("age","31");
int rows = userMapper.deleteByMap(columnMap);
System.out.println("影响行数:"+rows);
}
◆以条件构造器为参数的删除方法
ActiveRecord模式
AR探索
◆AR模式简介
◆MP中AR模式的实现