首页 > 其他分享 >二、基本CRUD

二、基本CRUD

时间:2023-02-22 17:02:30浏览次数:36  
标签:基本 queryWrapper CRUD param 查询 public user id

BaseMapper

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<?> 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 实体对象封装操作类
     * @return
     */
    default boolean exists(Wrapper<T> queryWrapper) {
        Long count = this.selectCount(queryWrapper);
        return null != count && count > 0;
    }

    /**
     * 根据 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(){
	//INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
	User user = new User();
	user.setName("张三");
	user.setAge(23);
	user.setEmail("[email protected]");
	int result = userMapper.insert(user);
	System.out.println("result:"+result);
	System.out.println("id:"+user.getId());
}

image
注意: 最终执行的结果,所获取的id为1628281806451220482这是因为MyBatis-Plus在实现插入数据时,会默认基于雪花算法的策略生成id。

删除

通过id删除记录

@Test
public void testDeleteById() {
	//DELETE FROM user WHERE id=?
	int result = userMapper.deleteById(1628281806451220482L);
	System.out.println("受影响行数:" + result);
}

image

通过id批量删除记录

@Test
public void testDeleteBatchIds() {
	//DELETE FROM user WHERE id IN ( ? , ? , ? )
	List<Long> idList = Arrays.asList(1L, 2L, 3L);
	int result = userMapper.deleteBatchIds(idList);
	System.out.println("result:" + result);
}

image

通过map条件删除记录

@Test
public void testDeleteByMap() {
	//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:" + result);
}

image

修改

@Test
public void testUpdateById(){
	//UPDATE user SET name=?, email=? WHERE id=?
	User user = new User();
	user.setId(4L);
	user.setName("李四");
	user.setEmail("[email protected]");
	int result = userMapper.updateById(user);
	System.out.println("result:"+result);
}

image

查询

根据id查询

@Test
public void testSelectById() {
	//SELECT id,name,age,email FROM user WHERE id=?
	User user = userMapper.selectById(4L);
	System.out.println(user);
}

image

根据多个id查询

@Test
public void testSelectBatchIds(){
	//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);
}

image

通过map条件查询

@Test
public void testSelectByMap() {
	//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);
}

image

查询所有数据

@Test
public void testSelectList() {
	// SELECT id,name,age,email FROM user
	List<User> users = userMapper.selectList(null);
	users.forEach(System.out::println);
}

image
注意: 通过观察BaseMapper中的方法,大多方法中都有Wrapper类型的形参,此为条件构造器,可针对于SQL语句设置不同的条件,若没有条件,则可以为该形参赋值null,即查询(删除/修改)所有数据。

自定义方法

mapper映射文件

image

<mapper namespace="com.study.demo.mapper.UserMapper">
    <!--Map<String, Object> selectMapById(Long id);-->
    <select id="selectMapById" resultType="map">
        select id,name,age,email from user where id = #{id}
    </select>
</mapper>

UserMapper接口

@Repository
public interface UserMapper extends BaseMapper<User> {
    /**
     * 根据id查询用户信息为map集合
     * @param id
     * @return
     */
    Map<String, Object> selectMapById(Long id);
}

测试

@Test
public void testSelectMapById() {
	//select id,name,age,email from user where id = ?
	Map<String, Object> map = userMapper.selectMapById(1L);
	System.out.println(map);
}

image

通用Service

  • 通用 Service CRUD 封装IService接口,进一步封装 CRUD 采用 get 查询单行 remove 删除 list 查询集合 page 分页 前缀命名方式区分 Mapper 层避免混淆,
  • 泛型 T 为任意实体对象
  • 建议如果存在自定义通用 Service 方法的可能,请创建自己的 IBaseService 继承 Mybatis-Plus 提供的基类

IService

MyBatis-Plus中有一个接口 IService和其实现类 ServiceImpl,封装了常见的业务层逻辑详情查看源码IService和ServiceImpl

创建Service接口和实现类

import com.baomidou.mybatisplus.extension.service.IService;
import com.study.demo.pojo.User;
/**
* UserService继承IService模板提供的基础功能
*/
public interface UserService extends IService<User> {
}
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.demo.mapper.UserMapper;
import com.study.demo.pojo.User;
import com.study.demo.service.UserService;
import org.springframework.stereotype.Service;

/**
 * ServiceImpl实现了IService,提供了IService中基础功能的实现
 * 若ServiceImpl无法满足业务需求,则可以使用自定的UserService定义方法,并在实现类中实现
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

测试查询记录数

@Test
public void testGetCount(){
	long count = userService.count();
	System.out.println("总记录数:" + count);
}

image

测试批量插入

@Test
public void testSaveBatch(){
	// SQL长度有限制,海量数据插入单条SQL无法实行,
	// 因此MP将批量插入放在了通用Service中实现,而不是通用Mapper
	ArrayList<User> users = new ArrayList<>();
	for (int i = 0; i < 5; i++) {
		User user = new User();
		user.setName("hjy" + i);
		user.setAge(20 + i);
		users.add(user);
	}
	userService.saveBatch(users);
}

image

标签:基本,queryWrapper,CRUD,param,查询,public,user,id
From: https://www.cnblogs.com/yellow-mokey/p/17144275.html

相关文章

  • 【MySQL】005-表的CRUD(增删改查)操作
    目录1、查询数据库中所有的表名称:二、创建1、语法格式2、MySQL中的数据类型(常用的)整型:int浮点型:double(参数1,参数2)日期(仅年月日):date日期:datetime时间戳:timest......
  • 企业管理漫谈丨节省时间提升效率,是管理的基本目标
    上周专程去JC公司做了一次客户回访,接待我的是JC公司负责信息化管理的两位老师,非常谦虚和开放,人很好!此次交流,让我收获颇多。每一次近距离地与客户接触,让我对企业经营管理方面......
  • Containerd安装配置及基本操作
    一、安装1.下载(https://github.com/containerd/containerd)wgethttps://github.com/containerd/containerd/releases/download/v1.6.10/cri-containerd-1.6.10-linux-amd64.......
  • 01 maven基本概述
    01maven安装和使用maven环境的安装下载Maven的安装包官网:https://maven.apache.org/download.cgi解压配置环境变量新建系统变量-->Path命令行测试m......
  • SPA路由实现的基本原理
    1.SPA路由实现的基本原理前端单页应用实现路由的策略有两种,分别是基于hash和基于HistoryAPI基于hash通过将一个URLpath用#Hash符号拆分。—浏览器视作其......
  • 【python】python基本语法
    字符串字符串是否包含子字符串两种方法:[find()][in]/[notin]//方法一ifstring1.find(string2):print("foundstring2instring1")//方法二ifstring2in......
  • Go 中的反射 reflect 介绍和基本使用
    一、什么是反射在计算机科学中,反射(英语:reflection)是指计算机程序在运行时(runtime)可以访问、检测和修改它本身状态或行为的一种能力。用比喻来说,反射就是程序在运行的时候......
  • JQuery事件绑定&入口函数&样式控制与JQuery_选择器_基本选择器
    JQuery事件绑定&入口函数&样式控制4.选择器:筛选具有相似特征的元素(标签)1.基本操作学习: 1.事件绑定 2.入口函数  ......
  • numpy数组的基本操作
    数组的基本操作1.数组的索引、切片一维、二维、三维的数组切片直接进行索引,切片对象[:,:]—先行后列#对于二维数组x1=np.random.uniform(0,1,[4,5])#生成一......
  • linux基本功系列之sudo命令实战
    #前言......