02 MP之基于Mapper接口/Service接口实现CRUD+分页(通用查询分页+自定义查询分页)

项目结构:
在这里插入图片描述

1.1 Insert方法
// 插入一条记录
// T 就是要插入的实体对象
// 默认主键生成策略为雪花算法(后面讲解)
//返回值是影响条数
int insert(T entity);
1.2 Delete方法
// 根据 entity 条件,删除记录
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);

// 删除(根据ID 批量删除)
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

// 根据 ID 删除
int deleteById(Serializable id);

// 根据 columnMap 条件,删除记录
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

在这里插入图片描述


何为Wrapper wrapper ?
执行语句时我们可能存在多个条件,例如同时要求年龄大于18,且为女生,此时把多个条件封装进其中,本质就是一个条件封装对象

何为Map<String,Object> ?
与Wrapper很相似 , 可以将 age =18 , sex = 1装入Map中 , 即封装多个键值对

Map map = new HashMap();
map.put("age",20);
int rows = userMapper.deleteByMap(map);

1.3 Update方法
// 第一个参数是要改的实体 , 第二个条件是判断的参数 ,根据 whereWrapper 条件,更新记录
int update(@Param(Constants.ENTITY) T updateEntity, 
            @Param(Constants.WRAPPER) Wrapper<T> whereWrapper);

// 根据 ID 修改  主键属性必须存在
int updateById(@Param(Constants.ENTITY) T entity);

在这里插入图片描述

//updateById,根据传入对象的主键值去更新剩余值
User user = new User();
user.setId(1L);
user.setAge(19);
//等价于 update user set age = 30 where id = 1
int rows = userMapper.updateById(user);

//update
User user = new User();
user.setAge(22);
//等价于 update user set age = 22 ,省略了判断条件,更新所有行的age为22
int rows = userMapper.update(user,null);
1.4 Select方法
// 根据 ID 查询
T selectById(Serializable id);

// 根据 entity 条件,查询一条记录
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

// 查询(根据ID 批量查询)
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

// 根据 entity 条件,查询全部记录
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

// 查询(根据 columnMap 条件)
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

// 根据 Wrapper 条件,查询全部记录
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

// 根据 Wrapper 条件,查询全部记录。注意: 只返回第一个字段的值
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

// 根据 entity 条件,查询全部记录(并翻页)
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

// 根据 Wrapper 条件,查询全部记录(并翻页)
IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

// 根据 Wrapper 条件,查询总记录数
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

在这里插入图片描述

1.5 自定义查询方法

如上所述,MP只为我们定义了单表的很多查询方法,如果是单表的一些特殊查询,亦或是多表查询,就需要自己编写语句了,方法如下:

在application.yaml中声明MP的默认mapperxml位置

mybatis-plus: # mybatis-plus的配置
  # 默认位置 private String[] mapperLocations = new String[]{"classpath*:/mapper/**/*.xml"};    
  mapper-locations: classpath:/mapper/*.xml

自定义mapper方法:

package com.sunsplanter.mapper
public interface UserMapper extends BaseMapper<User> {

    //正常自定义方法!
    //可以使用注解@Select或者mapper.xml实现
    List<User> queryAll();
}

基于mapper.xml实现:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace = 接口的全限定符 -->
<mapper namespace="com.sunsplanter.mapper.UserMapper">

   <select id="queryAll" resultType="user" >
       select * from user
   </select>
</mapper>

2 基于Service接口实现CRUD

原本 , service层提供逻辑服务 , 具体接触数据库由mapper实现:
在这里插入图片描述
现在 , 在service中也增加访问数据库的方式 , 于是 , 对于一些简单的项目(例如无需业务逻辑) , 就没必要再写mapper.

2.1 对比Mapper接口CRUD区别:
  • service添加了批量方法
  • service层的方法自动添加事务
2.2 使用Iservice接口方式

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

定义一个UserService接口继承IService接口

//IService中包含了很多CRUD方法 , 只要指定实体类泛型即可
public interface UserService extends IService<User> {

}

定义一个UserServiceImpl类继承ServiceImpl实现类+实现UserService接口,获得完整的CRUD方法


@Service
//在继承了ServiceImpl的同时实现了UserService接口
//实现了UserService,而UserService继承自IService, IService实现了一半的CRUD,故实现UserService接口即可获得一半的CRUD
//继承了SericeImpl,获得另一半的CRUD方法
//ServiceImpl第一个参数为继承自BaseMapper的xxxMapper,第二个参数为实体对象
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{

}
public interface UserMapper extends BaseMapper<User> {
    //之前,mapper接口内要声明抽象方法,然后再mapper.xml中具体写查询语句
    //List<User> queryAll();

    //现在,继承自BaseMapper,其内已定义了几乎所有单表查询语句
    //故UserMapper也拥有了这些方法,无需再写
}

结构如图,在test中编写测试方法.
在这里插入图片描述

2.3 CRUD方法介绍
保存:
// 插入一条记录(选择字段,策略插入)
boolean save(T entity);
// 插入(批量)
boolean saveBatch(Collection<T> entityList);
// 插入(批量)
boolean saveBatch(Collection<T> entityList, int batchSize);

//修改或者保存:
// 查询该entity的id去数据库中查询,如果存在对应的表项则更新,否则插入
boolean saveOrUpdate(T entity);
// 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);

移除:
// 根据 queryWrapper 设置的条件,删除记录
boolean remove(Wrapper<T> queryWrapper);
// 根据 ID 删除
boolean removeById(Serializable id);
// 根据 columnMap 条件,删除记录
boolean removeByMap(Map<String, Object> columnMap);
// 删除(根据ID 批量删除)
boolean removeByIds(Collection<? extends Serializable> idList);

更新:
// 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
boolean update(Wrapper<T> updateWrapper);
// 根据 whereWrapper 条件,更新记录
boolean update(T updateEntity, Wrapper<T> whereWrapper);
// 根据 ID 选择修改
boolean updateById(T entity);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList, int batchSize);

数量: 
// 查询总记录数
int count();
// 根据 Wrapper 条件,查询总记录数
int count(Wrapper<T> queryWrapper);

查询:
// 根据 ID 查询
T getById(Serializable id);
// 根据 Wrapper,查询一条记录。结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")
T getOne(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
T getOne(Wrapper<T> queryWrapper, boolean throwEx);
// 根据 Wrapper,查询一条记录
Map<String, Object> getMap(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);

集合:
// 查询所有
List<T> list();
// 查询列表
List<T> list(Wrapper<T> queryWrapper);
// 查询(根据ID 批量查询)
Collection<T> listByIds(Collection<? extends Serializable> idList);
// 查询(根据 columnMap 条件)
Collection<T> listByMap(Map<String, Object> columnMap);
// 查询所有列表
List<Map<String, Object>> listMaps();
// 查询列表
List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper);
// 查询全部记录
List<Object> listObjs();
// 查询全部记录
<V> List<V> listObjs(Function<? super Object, V> mapper);
// 根据 Wrapper 条件,查询全部记录
List<Object> listObjs(Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录
<V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);

1. 分页查询

  1. 在启动类MainApplication中配置拦截器(插件). MP有一个拦截器集合MybatisPlusInterceptor(包括分页插件/乐观锁) , new出这个拦截器集合后 , 将分页拦截器加入该集合 . 再将这个集合对象返回 ,

1.1 简单查询通过MP提供的方法实现分页(分页拦截器)

分页的本质就是需要设置一个拦截器,通过拦截器拦截了SQL,通过在SQL语句的结尾添加limit关键字,来实现分页的效果.

1.1.1 测试方法版

我们只是为了测试分页功能, 没必要再构建三层架构, 并逐层修改代码,太过于复杂.

1.1.1.1 新增一个MP配置类并添加分页拦截器

@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

1.1.2 创建一个分页查询对象放进wrapper中即可

@Test
void selectPage(){
    //1.创建QueryWrapper对象
    LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    //2.创建分页查询对象,指定当前页和每页显示条数
    IPage<User> page = new Page<>(1,3);
    //3.执行分页查询
    userMapper.selectPage(page, lambdaQueryWrapper);
    //4.查看分页查询的结果
    System.out.println("当前页码值:"+page.getCurrent());
    System.out.println("每页显示数:"+page.getSize());
    System.out.println("总页数:"+page.getPages());
    System.out.println("总条数:"+page.getTotal());
    System.out.println("当前页数据:"+page.getRecords());
}

可以看到, 很少的操作即可实现分页, 无需在SQL层面增加代码.

1.1.2 三层架构版

作为测试方法版的对比, 看看完整三层架构中,是如何简单实现分页的.

需求: 查找年龄为18的用户并分页展示

1.1.2.1 新增一个MP配置类并添加分页拦截器(完全一样)
1.1.2.2 Mapper 接口
public interface UserMapper extends BaseMapper<User> {
    // 这里可以添加自定义的方法,也可以使用 MyBatis Plus 内置的CRUD方法
}
1.1.2.3 service层

@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Autowired
    private UserMapper userMapper;

    public Page<User> getUsersByAge(int age, int pageNum, int pageSize) {
        // 创建 QueryWrapper 对象,用于构建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("age", 18); // 设置查询条件,年龄等于18

        // 创建 Page 对象,用于分页查询
        Page<User> page = new Page<>(pageNum, pageSize);

        // 执行分页查询
        return userMapper.selectPage(page, queryWrapper);
    }
}
1.1.2.4 controller层
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/byAge")
    public Page<User> getUsersByAge(
            @RequestParam("age") int age,
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        return userService.getUsersByAge(age, pageNum, pageSize);
    }
}

1.2 自定义分页插件

在某些场景下,我们需要自定义SQL语句来进行查询。

这种情况下

  1. mapperxml文件中手写SQL
  2. mapper接口必须要声明自定义的查询了
  3. service, controller层调用的方法做相应更改

1.2.1 测试方法版

1.2.1.1 mapperxml
<?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.powernode.mapper.UserMapper">

     <select id="selectByName" resultType="com.powernode.domain.User">
        select * from powershop_user where name = #{name}
     </select>

</mapper>
1.2.1.2 mapper接口
@Mapper
public interface UserMapper extends BaseMapper<User> {
       IPage<User> selectByName(IPage<User> page, String name);
}
1.2.1.3 单元测试
@Test
void selectPage2(){
    //1.创建分页查询对象,指定当前页和每页显示条数
    IPage<User> page = new Page<>(1,2);
    //2.执行分页查询
    userMapper.selectByName(page,"Mary");
    //3.查看分页查询的结果
    System.out.println("当前页码值:"+page.getCurrent());
    System.out.println("每页显示数:"+page.getSize());
    System.out.println("总页数:"+page.getPages());
    System.out.println("总条数:"+page.getTotal());
    System.out.println("当前页数据:"+page.getRecords());
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值