MyBatisPlus基本增删改查(BaseMapper的使用方法)

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<? 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);
}

创建测试类

MyBatisPlusTest

@SpringBootTest
public class MyBatisPlusTest {
    @Autowired
    private UserMapper userMapper;
}

1.插入

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

最终执行的结果,所获取的id为1821031534634205185
这是因为MyBatis-Plus在实现插入数据时,会默认基于雪花算法的策略生成id
因此,数据库建表时id使用bigint类型

2.删除

1.通过id删除记录

@Test
    public void testDeleteById() {
        //使用1821031534634205185L而不使用1821031534634205185,因为1821031534634205185已经超出int的范围了
        //通过id删除用户信息
        //DELETE FROM user WHERE id=?
        int res = userMapper.deleteById(1821031534634205185L);
        System.out.println(res);
    }

2.通过id批量删除记录

@Test
    public void testDeleteBatchIds() {
        //通过多个id批量删除
        //DELETE FROM user WHERE id IN ( ? , ? , ? )
        List<Long> list = new ArrayList<>();
        //删除id为2、173873847468448、8的数据
        list.add(2L);
        list.add(173873847468448L);
        list.add(8L);
        int res = userMapper.deleteBatchIds(list);
        System.out.println(res);
    }

3.通过map条件删除记录

@Test
    public void testDeleteByMap() {
        //根据map集合中所设置的条件删除记录
        //DELETE FROM user WHERE name = ? AND age = ?
        Map<String,Object> map = new HashMap<>();
        map.put("age",28);
        map.put("name","Tom");
        int res = userMapper.deleteByMap(map);
        System.out.println(res);
    }

3.查询

1.根据id查询用户信息

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

2.根据多个id查询多个用户信息

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

3.通过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("name", "Billie");
        map.put("age", 23);
        List<User> res = userMapper.selectByMap(map);
        res.forEach(System.out::println);
    }

4.查询所有数据

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

4.自定义功能

MyBatisPlus适用于单表的操作,但是BaseMapper中的功能无法满足我们的需求时(如实现联表查询),便可以自定义sql语句进行操作(毕竟MyBatisPlus在MyBatis的基础上,只做增强不做改变),之前MyBatis怎么实现现在MyBatisPlus便怎么实现。
已经创建了UserMapper,便继续创建其映射文件
在这里插入图片描述
接下来以根据id查询用户信息为map集合为例

  • 在UserMapper中创建方法
@Repository
public interface UserMapper extends BaseMapper<User> {
    /**
     * 根据id查询用户信息为map集合
     * @param id
     * @return
     */
    Map<String, Object> selectMapById(Long id);
}
  • 在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.yolo.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() {
        //自定义方法根据id查询用户信息为map集合
        Map<String, Object> map = userMapper.selectMapById(7L);
        System.out.println(map);
    }

注:上述内容参考自尚硅谷

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis Plus 是一个开源的 MyBatis 增强工具,它简化了与数据库的交互过程,提供了许多方便易用的功能。下面我将以300字介绍 MyBatis Plus 如何生成增删改查和文件下载的功能。 首先,MyBatis Plus 提供了代码生成器,可以根据数据库表的结构自动生成实体类、Mapper 接口和 XML 映射文件。我们只需要配置好数据库连接和相关参数,运行代码生成器,即可生成基本增删改查代码。 生成的代码遵循了 MyBatis 的规范,我们可以在生成的实体类中定义表的字段,并使用注解指定与数据库的映射关系。通过继承 MyBatis Plus 提供的 BaseMapper 接口,我们可以轻松地实现基本增删改查操作,无需手动编写 SQL 语句。 除了基本增删改查MyBatis Plus 还提供了一些高级的查询功能。例如,我们可以使用 Wrapper 来构建复杂的查询条件,支持分页查询、排序等。同时,MyBatis Plus 还支持批量操作,可以一次性插入多个实体对象,提高了数据的处理效率。 对于文件下载的功能,我们可以使用 MyBatis Plus 的文件上传下载组件进行处理。通过配置文件上传的目录,我们可以将文件保存到指定的位置。而文件下载则可以通过在 Controller 中编写对应的接口方法,根据文件的路径将文件返回给用户。 总结来说,MyBatis Plus 提供了代码生成器来生成基本增删改查代码,简化了与数据库的交互。它还支持复杂的查询条件、批量操作和文件上传下载等功能,方便开发者进行数据库操作和文件处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值