MyBatisPlus —— 2、基本CRUD

目录

1、BaseMapper

2、插入

3、删除

4、修改

5、查询

6、自定义SQL(使用xml配置)进行非单表查询等操作

7、通用 Service

7.1、IService

7.2、创建Service接口及其实现类

7.3、测试查询记录数

7.4、测试批量添加


1、BaseMapper

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.baomidou.mybatisplus.core.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;

public interface BaseMapper<T> extends Mapper<T> {
    /**
     * 插入一条记录
     * @param entity 实体对象
     * @return
     */
    int insert(T entity);

    /**
     * 根据ID删除
     * @param id 主键id
     * @return
     */
    int deleteById(Serializable id);

    /**
     * 根据实体ID删除
     * @param entity 实体对象
     * @return
     */
    int deleteById(T entity);

    /**
     * 根据columnMap条件删除记录
     * @param columnMap 表字段map对象
     * @return
     */
    int deleteByMap(@Param("cm") Map<String, Object> columnMap);

    /**
     * 根据entity条件删除记录
     * @param queryWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
     * @return
     */
    int delete(@Param("ew") Wrapper<T> queryWrapper);

    /**
     * 删除(根据ID 批量删除)
     * @param idList 主键ID列表(不能为 null 以及 empty)
     * @return
     */
    int deleteBatchIds(@Param("coll") Collection<?> idList);

    /**
     * 根据 ID 修改,不会修改没有使用 set 注入属性的属性值
     * @param entity 实体对象
     * @return
     */
    int updateById(@Param("et") T entity);

    /**
     * 根据 whereEntity 条件,更新记录
     * @param entity 实体对象 (set 条件值,可以为 null)
     * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
     * @return
     */
    int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);

    /**
     * 根据 ID 查询
     * @param id 主键ID
     * @return
     */
    T selectById(Serializable id);

    /**
     * 查询(根据ID 批量查询)
     * @param idList 主键ID列表(不能为 null 以及 empty)
     * @return
     */
    List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);

    /**
     * 查询(根据 columnMap 条件)
     * @param columnMap 表字段 map 对象
     * @return
     */
    List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);

    /**
     * 根据 entity 条件,查询一条记录
     * 查询一条记录,例如 qw.last("limit 1") 限制取一条记录, 注意:多条数据会报异常
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     * @return
     */
    default T selectOne(@Param("ew") 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", new Object[0]);
            } else {
                return ts.get(0);
            }
        } else {
            return null;
        }
    }

    /**
     * 根据 Wrapper 条件,查询总记录数
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     * @return
     */
    default boolean exists(Wrapper<T> queryWrapper) {
        Long count = this.selectCount(queryWrapper);
        return null != count && count > 0L;
    }

    /**
     * 根据 Wrapper 条件,查询总记录数
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     * @return
     */
    Long selectCount(@Param("ew") Wrapper<T> queryWrapper);

    /**
     * 根据 entity 条件,查询全部记录
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     * @return
     */
    List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     * @return
     */
    List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录
     * 注意: 只返回第一个字段的值
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     * @return
     */
    List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);

    /**
     * 根据 entity 条件,查询全部记录(并翻页)
     * @param page 分页查询条件(可以为 RowBounds.DEFAULT)
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     * @param <P>
     * @return
     */
    <P extends IPage<T>> P selectPage(P page, @Param("ew") Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录(并翻页)
     * @param page 分页查询条件
     * @param queryWrapper 实体对象封装操作类
     * @param <P>
     * @return
     */
    <P extends IPage<Map<String, Object>>> P selectMapsPage(P page, @Param("ew") Wrapper<T> queryWrapper);
}

2、插入

    @Test
    public void testInsert(){
        User user = new User();
        user.setName("王五");
        user.setAge(46);
        user.setEmail("[email protected]");
        //
        int result = userMapper.insert(user);
        System.out.println("result = " + result);
        System.out.println("id = " + user.getId()); //这里获取的id是mybatis-plus通过雪花算法得到的
    }

3、删除

    @Test
    public void testDelete(){
        // 通过id删除用户信息
        // DELETE FROM user WHERE id=?
        /*int result = userMapper.deleteById(1512743678382899202L);
        System.out.println("result = " + result);*/

        // 根据map集合中所设置的条件删除用户信息
        /*Map<String, Object> map = new HashMap<>();
        map.put("name", "王五");
        map.put("age", "46");
        // DELETE FROM user WHERE name = ? AND age = ?
        int result = userMapper.deleteByMap(map);
        System.out.println("result = " + result);*/

        // 通过多个ID实现批量删除
        List<Long> list = Arrays.asList(1512743901935067138L, 0L);
        // DELETE FROM user WHERE id IN ( ? , ? )
        int result = userMapper.deleteBatchIds(list);
        System.out.println("result = " + result);
    }

4、修改

    @Test
    public void testUpdate(){
        User user = new User();
        user.setId(1L);
        user.setName("李四");
        user.setEmail("[email protected]");
        // UPDATE user SET name=?, email=? WHERE id=?
        // 不会修改没有set的属性值
        int result = userMapper.updateById(user);
        System.out.println("result = " + result);
    }

5、查询

    @Test
    public void testSelect(){
        // 通过ID查询用户信息
        /*// SELECT id,name,age,email FROM user WHERE id=?
        User user = userMapper.selectById(1L);
        System.out.println(user);*/

        // 根据多个ID查询多个用户信息
        /*List<Long> list = Arrays.asList(1L, 2L, 3L);
        // SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? )
        List<User> users = userMapper.selectBatchIds(list);
        users.forEach(System.out::println);*/

        // 根据Map集合中的条件查询用户信息
        /*Map<String, Object> map = new HashMap<>();
        map.put("name", "Jack");
        map.put("age", 20);
        // SELECT id,name,age,email FROM user WHERE name = ? AND age = ?
        List<User> users = userMapper.selectByMap(map);
        users.forEach(System.out::println);*/

        // 查询所有数据
        // SELECT id,name,age,email FROM user
        List<User> users = userMapper.selectList(null);
        users.forEach(System.out::println);
    }

6、自定义SQL(使用xml配置)进行非单表查询等操作

mybatis-plus 中默认读取的 XxxMapper.xml 的位置是在 src/main/resources/mapper 下的所有 xml 文件(可以包含任意层目录),所以我们可以不用自己设定 XxxMapper.xml 的位置

 mapper 接口:UserMapper

@Mapper
//@Repository  //将该类或接口标识为持久层组件
public interface UserMapper extends BaseMapper<User> {

    /**
     * 根据id查询用户信息为map集合
     * @param id
     * @return
     */
    Map<String, Object> selectMapById(Long id);

}

配置文件:UserMapper.xml

<?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.zyj.mybatisplus.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>

测试方法:

    @Test
    public void testSelectMapById(){
        Map<String, Object> map = userMapper.selectMapById(1L);
        System.out.println(map);
    }

输出结果:

==>  Preparing: select id,name,age,email from user where id = ?
==> Parameters: 1(Long)
<==    Columns: id, name, age, email
<==        Row: 1, 李四, 18, [email protected]
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@65753040]
{name=李四, id=1, age=18, [email protected]}

7、通用 Service

说明:

  • 通用 Service CRUD 封装IService接口,进一步封装 CRUD 采用 get 查询单行 remove 删 除 list 查询集合 page 分页 前缀命名方式区分 Mapper 层避免混淆,

  • 泛型 T 为任意实体对象

  • 建议如果存在自定义通用 Service 方法的可能,请创建自己的 IBaseService 继承Mybatis-Plus 提供的基类

  • 官网地址:CRUD 接口 | MyBatis-Plus

7.1、IService

MyBatis-Plus中有一个接口 IService和其实现类 ServiceImpl,封装了常见的业务层逻辑。详情查看源码IService和ServiceImpl(由于是国人写的,所以里面的注释是中文)

7.2、创建Service接口及其实现类

public interface UserService extends IService<User> {


}
@Service
// ServiceImpl<mapper接口, 实体类>
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


}

7.3、测试查询记录数

测试方法:

public class MyBatisPlusServiceTest {

    @Autowired
    private UserService userService;

    @Test
    public void testGetCount(){
        // 查询总记录数
        // SELECT COUNT( * ) FROM user
        long count = userService.count();
        System.out.println("总记录数 = " + count);
    }

}

输出结果:

==>  Preparing: SELECT COUNT( * ) FROM user
==> Parameters: 
<==    Columns: COUNT( * )
<==        Row: 5
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@238bfd6c]
总记录数 = 5

7.4、测试批量添加

测试方法: 

    @Test
    public void testInsertMore(){
        // 批量添加
        // Preparing: INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
        List<User> list = new ArrayList<>();
        for(int i = 0; i < 10; i++){
            User user = new User();
            user.setName("张" + i);
            user.setAge(20 + i);
            user.setEmail("zhang" + i + "@qq.com");
            list.add(user);
        }
        boolean b = userService.saveBatch(list);
        System.out.println(b);
    }

输出结果:

==>  Preparing: INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
==> Parameters: 1513090537404141570(Long), 张0(String), 20(Integer), [email protected](String)
==> Parameters: 1513090537634828289(Long), 张1(String), 21(Integer), [email protected](String)
==> Parameters: 1513090537634828290(Long), 张2(String), 22(Integer), [email protected](String)
==> Parameters: 1513090537634828291(Long), 张3(String), 23(Integer), [email protected](String)
==> Parameters: 1513090537634828292(Long), 张4(String), 24(Integer), [email protected](String)
==> Parameters: 1513090537634828293(Long), 张5(String), 25(Integer), [email protected](String)
==> Parameters: 1513090537634828294(Long), 张6(String), 26(Integer), [email protected](String)
==> Parameters: 1513090537634828295(Long), 张7(String), 27(Integer), [email protected](String)
==> Parameters: 1513090537634828296(Long), 张8(String), 28(Integer), [email protected](String)
==> Parameters: 1513090537634828297(Long), 张9(String), 29(Integer), [email protected](String)
true

猜你喜欢

转载自blog.csdn.net/Mr_zhangyj/article/details/124063611