当前位置: 首页 > news >正文

MyBatis-Plus中使用BaseMapper实现基本CRUD

MyBatis-Plus中的基本CRUD在内置的BaseMapper中都已得到了实现,我们可以直接使用,接口如 下:

package com.baomidou.mybatisplus.core.mapper;

public interface BaseMapper<T> extends Mapper<T> {

/**

* 插入一条记录

* @param entity 实体对象 */

int insert(T entity);

/**

* 根据 ID 删除

* @param id 主键ID */

int deleteById(Serializable id);

/**

* 根据实体(ID)删除

* @param entity 实体对象

* @since 3.4.4 */

int deleteById(T entity);

/**

* 根据 columnMap 条件,删除记录

* @param columnMap 表字段 map 对象 */

int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

/**

* 根据 entity 条件,删除记录

* @param queryWrapper 实体对象封装操作类(可以为 null,里面的 entity 于生成 where

语句)

*/

int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

/**

* 删除(根据ID 批量删除)

* @param idList 主键ID列表(不能为 null 以及 empty) */

int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

/**

* 根据 ID 修改

* @param entity 实体对象 */

int updateById(@Param(Constants.ENTITY) T entity);

/**

* 根据 whereEntity 条件,更新记录

* @param entity        实体对象 (set 条件值 ,可以为 null)

* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 于生成

where 语句)

*/

int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);

/**

* 根据 ID 查询

* @param id 主键ID */

T selectById(Serializable id);

/**

* 查询(根据ID 批量查询)

* @param idList 主键ID列表(不能为 null 以及 empty) */

List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

/**

* 查询(根据 columnMap 条件)

* @param columnMap 表字段 map 对象 */

List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

/**

* 根据 entity 条件,查询一条记录

* <p>查询一条记录,例如 qw.last("limit 1") 限制取一条记录 , 注意:多条数据会报异常 </p>

* @param queryWrapper 实体对象封装操作类(可以为 null

*/

default T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper) { List<T> ts = this.selectList(queryWrapper);

if (CollectionUtils.isNotEmpty(ts)) {

if (ts.size() != 1) {

throw ExceptionUtils.mpe("One record is expected, but the query result is multiple records");

}

return ts.get(0);

}

return null;

}

/**

* 根据 Wrapper 条件,查询总记录数

* @param queryWrapper 实体对象封装操作类(可以为 null */

Long selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

/**

* 根据 entity 条件,查询全部记录

* @param queryWrapper 实体对象封装操作类(可以为 null */

List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

/**

* 根据 Wrapper 条件,查询全部记录

* @param queryWrapper 实体对象封装操作类(可以为 null */

List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

/**

* 根据 Wrapper 条件,查询全部记录

* <p>注意: 只返回第一个字段的值</p>

* @param queryWrapper 实体对象封装操作类(可以为 null */

List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

/**

* 根据 entity 条件,查询全部记录(并翻页)

* @param page         分页查询条件(可以为 RowBounds.DEFAULT

* @param queryWrapper 实体对象封装操作类(可以为 null */

<P extends IPage<T>> P selectPage(P page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

/**

* 根据 Wrapper 条件,查询全部记录(并翻页)

* @param page         分页查询条件

* @param queryWrapper 实体对象封装操作类 */

<P extends IPage<Map<String, Object>>> P selectMapsPage(P page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

}

 插入

 

@Test
public void testInsert(){User user = new User(null, "张三", 23, "zhangsan@qcby.com");//INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )int result = userMapper.insert(user);System.out.println("受影响行数:"+result);//1948652625792266241System.out.println("id自动获取:"+user.getId());
}

 删除

通过id删除记录

 

@Test
public void testDeleteById(){//通过id删除用户信息//DELETE FROM user WHERE id=?int result = userMapper.deleteById(1948651568068509697l);System.out.println("受影响行数:"+result);
}

@Test
public void testDeleteByIdWithEntity() {// deleteById(T entity):本质还是根据主键ID删除(从实体中取ID)// DELETE FROM user WHERE id = ?User user = new User();user.setId(8L); // 必须设置主键ID,否则无法删除// 其他字段不会影响删除(只认主键)user.setName("不重要的名字");int result = userMapper.deleteById(user);System.out.println("根据实体中的ID删除,受影响行数:" + result);
}

 通过id批量删除记录

@Test

public void testDeleteBatchIds(){

//通过多个id批量删除

//DELETE FROM user WHERE id IN ( ? , ? , ? )

List<Long> idList = Arrays.asList(1L, 2L, 3L);

int result = userMapper.deleteBatchIds(idList);

System.out.println("受影响行数:"+result);

}

 

通过map条件删除记录

@Test

public void testDeleteByMap(){

//根据map集合中所设置的条件删除记录

//DELETE FROM user WHERE name = ? AND age = ?

Map<String, Object> map = new HashMap<>();

map.put("age", 23);

map.put("name", "张三");

int result = userMapper.deleteByMap(map);

System.out.println("受影响行数:"+result);

}

通过条件删除

@Test
public void testDeleteByWrapper() {// 根据条件删除用户信息// DELETE FROM user WHERE name = ? AND age = ?QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.eq("name", "测试用户")  // 条件1:姓名为"测试用户".eq("age", 20);         // 条件2:年龄为20int result = userMapper.delete(queryWrapper);System.out.println("受影响行数:" + result);
}@Test
public void testDeleteByWrapper2() {// 根据条件删除用户信息(另一种条件示例)// DELETE FROM user WHERE email IS NULLQueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.isNull("email");  // 条件:邮箱为空int result = userMapper.delete(queryWrapper);System.out.println("受影响行数:" + result);
}

修改

通过id修改

@Test
public void testUpdateById(){User user = new User(4L, "admin", 22, null);
//UPDATE user SET name=?, age=? WHERE id=?int result = userMapper.updateById(user);System.out.println("受影响行数:"+result);
}

通过条件修改

@Test
public void testUpdate(){// 假设有一个 UpdateWrapper 对象,设置查询条件为 age > 25,更新满足条件的用户的邮箱UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();updateWrapper.gt("age", 25);User updateUser = new User();updateUser.setEmail("new.email@example.com");int rows = userMapper.update(updateUser, updateWrapper); // 调用 update 方法if (rows > 0) {System.out.println("Users updated successfully.");} else {System.out.println("No users updated.");}
}

查询

通过id查找

@Test
public void testSelectById(){
//根据id查询用户信息
//SELECT id,name,age,email FROM user WHERE id=?User user = userMapper.selectById(4L);System.out.println(user);
}

通过条件查询

@Test
public void testSelectOne(){
//根据条件查询用户信息
//SELECT id,name,age,email FROM user WHERE name = ? AND age = ?QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.eq("name", "admin2").eq("age", 22);User user = userMapper.selectOne(queryWrapper);System.out.println(user);/*// 假设有一个 QueryWrapper 对象,设置查询条件为 age > 25,查询一条满足条件的用户QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.gt("age", 25);User user = userMapper.selectOne(queryWrapper); // 调用 selectOne 方法System.out.println("User: " + user);*/
}

通过id查询多个

@Test
public void testSelectBatchIds(){
//根据多个id查询多个用户信息
//SELECT id,name,age,email FROM user WHERE id IN ( ? , ? )List<Long> idList = Arrays.asList(4L, 5L);List<User> list = userMapper.selectBatchIds(idList);list.forEach(System.out::println);
}

通过map条件查询用户信息

@Test
public void testSelectByMap(){
//通过map条件查询用户信息
//SELECT id,name,age,email FROM user WHERE name = ? AND age = ?Map<String, Object> map = new HashMap<>();map.put("age", 22);map.put("name", "admin");List<User> list = userMapper.selectByMap(map);list.forEach(System.out::println);
}

结果list输出

@Test public void testSelectList(){ //selectList()根据MP内置的条件构造器查询一个list集合,null表示没有条件,即查询所有 userMapper.selectList(null).forEach(System.out::println); } 

结果映射为map

@Test
public void testSelectMaps(){// 假设有一个 QueryWrapper 对象,设置查询条件为 age > 25,查询所有满足条件的用户,并将结果映射为 MapQueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.gt("age", 25);List<Map<String, Object>> userMaps = userMapper.selectMaps(queryWrapper); // 调用 selectMaps 方法for (Map<String, Object> userMap : userMaps) {System.out.println("User Map: " + userMap);}
}

查询第一个字段

@Test
public void testSelectObjs(){// 假设有一个 QueryWrapper 对象,设置查询条件为 age > 25,查询所有满足条件的用户,并返回一个包含用户ID的列表QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.gt("age", 25);List<Object> userIds = userMapper.selectObjs(queryWrapper); // 调用 selectObjs 方法for (Object userId : userIds) {System.out.println("User ID: " + userId);}
}

分页查询

要先写一个配置类

package com.qcby.mybatisplus1.config;import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration // 标识为配置类
public class MyBatisPlusConfig {/*** 注册分页插件*/@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();// 添加分页插件,指定数据库类型(MySQL)interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}
}

//selectPage
@Test
public void testSelectPage(){//SELECT * FROM user WHERE age > 25 LIMIT 2 OFFSET 0// 假设要进行分页查询,每页显示2条记录,查询第1页,查询条件为 age > 25IPage<User> page = new Page<>(1, 2);QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.gt("age", 25);IPage<User> userPage = userMapper.selectPage(page, queryWrapper); // 调用 selectPage 方法List<User> userList = userPage.getRecords();long total = userPage.getTotal();System.out.println("Total users (age > 25): " + total);for (User user : userList) {System.out.println("User: " + user);}
}

map

@Test
public void testSelectMapsPage(){// 假设要进行分页查询,每页显示2条记录,查询第1页,查询条件为 age > 25,并将结果映射为 MapIPage<Map<String, Object>> page= new Page<>(1, 2);QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.gt("age", 25);IPage<Map<String, Object>> userPageMaps = userMapper.selectMapsPage(page, queryWrapper); // 调用 selectMapsPage 方法List<Map<String, Object>> userMapList = userPageMaps.getRecords();long total = userPageMaps.getTotal();System.out.println("Total users (age > 25): " + total);for (Map<String, Object> userMap : userMapList) {System.out.println("User Map: " + userMap);}
}

查询数量

@Test
public void testSelectCount(){//SELECT COUNT( * ) FROM user WHERE age > 25QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.gt("age", 25);long count = userMapper.selectCount(queryWrapper); // 调用 selectCount 方法System.out.println("Count of users (age > 25): " + count);
}

查询是否存在

/*** 测试exists方法:验证符合条件的记录是否存在*/@Testpublic void testExists() {// 1. 测试存在的情况:查询age > 30的用户是否存在QueryWrapper<User> existsWrapper = new QueryWrapper<>();existsWrapper.gt("age", 28); // 假设数据库中有age>28的用户boolean isExists = userMapper.exists(existsWrapper);System.out.println("age > 28的用户是否存在:" + isExists);// 如果确定有符合条件的数据,可以使用断言验证assertTrue(isExists, "age > 28的用户应该存在");//        // 2. 测试不存在的情况:查询name = "不存在的用户"的记录
//        QueryWrapper<User> notExistsWrapper = new QueryWrapper<>();
//        notExistsWrapper.eq("name", "不存在的用户"); // 假设该用户不存在
//        boolean isNotExists = userMapper.exists(notExistsWrapper);
//        System.out.println("name = '不存在的用户'的记录是否存在:" + isNotExists);// 如果确定无符合条件的数据,可以使用断言验证// assertFalse(isNotExists, "name = '不存在的用户'的记录应该不存在");}

 

http://www.xdnf.cn/news/1186705.html

相关文章:

  • spring boot整合mybatis
  • Haprxy七层代理
  • MyBatisPlus(一)简介与基本CRUD
  • 开疆智能ModbusTCP转Profient网关连接西门子PLC与川崎机器人配置案例
  • leetcode933最近的请求次数
  • 继承接口实现websocke,实现任意路径链接
  • Java 流(Stream)分类、用途与性能分析
  • 黑马点评01 - 项目介绍 短信登录
  • 【C#补全计划:类和对象(七)—— 重写虚方法】
  • 屏幕适配--像素篇
  • C/C++---I/O性能优化
  • Linux的磁盘存储管理实操——(下二)——逻辑卷管理LVM的扩容、缩容
  • 小白如何认识并处理Java异常?
  • gig-gitignore工具实战开发(三):gig add基础实现
  • 双指针算法介绍及使用(下)
  • which soffice soffice not found
  • OpenRLHF:面向超大语言模型的高性能RLHF训练框架
  • 机器学习之knn算法保姆级教学
  • SEC_FirePower 第二天作业
  • Keepalived 原理及配置(高可用)
  • ubuntu22.04.4锁定内核应对海光服务器升级内核无法启动问题
  • 【Docker项目实战】在Docker环境下部署go-file文件分享工具
  • 5G基站信号加速器!AD8021ARZ-REEL7亚德诺 超低噪声高速电压放大器 专利失真消除技术!
  • 从零开发Java坦克大战:架构设计与难点突破 (下)
  • C++ 多线程同步机制详解:互斥锁、条件变量与原子操作
  • 电子电气架构 --- 车载软件与样件产品交付的方法
  • TDengine 转化函数 TO_TIMESTAMP 用户手册
  • Python 程序设计讲义(21):循环结构——while循环
  • Leetcode力扣解题记录--第21题(合并链表)
  • C++ 常用的数据结构(适配器容量:栈、队列、优先队列)