Data Access 之 MyBatis Plus(三)- MPG代码生成器(Part B)

简介: Data Access 之 MyBatis Plus(三)- MPG代码生成器(Part B)

四、MPG 的 IService 接口

MPG代码生成器生成的Service接口继承了MP的IService接口,该接口除了基本的增删改查外,还包含了一些批量操作方法,该接口中定义的方法除了default方法外都在ServiceImpl类中实现了

public interface ITeslaService extends IService<Tesla> {
}
复制代码

IService 接口的 save 相关方法

// 插入一条记录(选择字段,策略插入), 直接调用的BaseMapper的insert()方法
default boolean save(T entity) {
// 插入(批量)
default boolean saveBatch(Collection<T> entityList)
// 插入(批量)
boolean saveBatch(Collection<T> entityList, int batchSize);
// 批量修改插入
default boolean saveOrUpdateBatch(Collection<T> entityList) {
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);
复制代码

在ITeslaServiceTest测试类中增加相应的测试方法

@Test
public void saveBatch(){
    List<Tesla> teslaList = new ArrayList<>();
    for (int i = 0; i < 5; i++) {
        Tesla tesla = new Tesla();
        tesla.setName("Cyber Truck 202" + i);
        tesla.setFactory("得克萨斯州特斯拉超级工厂");
        tesla.setVehicleType("皮卡");
        tesla.setPrice(300000.00 + 1000 * i);
        teslaList.add(tesla);
    }
    boolean b = teslaService.saveBatch(teslaList);
    System.out.println("是否保存成功:" + b);
}
复制代码

执行该测试方法

image.png

保存成功,控制台只执行了一次SQL将数据全部保存到表中

@Test
public void saveBatchByBatchSize(){
    List<Tesla> teslaList = new ArrayList<>();
    for (int i = 0; i < 5; i++) {
        Tesla tesla = new Tesla();
        tesla.setName("Cyber Truck 202" + i);
        tesla.setFactory("上海特斯拉超级工厂");
        tesla.setVehicleType("皮卡");
        tesla.setPrice(300000.00 + 1000 * i);
        teslaList.add(tesla);
    }
    boolean b = teslaService.saveBatch(teslaList, 2);
    System.out.println("是否保存成功:" + b);
}
复制代码

执行该测试方法

image.png

批量保存时设置类batchSize,既每次执行批量插入时只插入两条数据,因此控制台执行了3次SQL语句

@Test
public void saveOrUpdateBatch(){
    List<Tesla> updateList = new ArrayList<>();
    for (int i = 1166057549; i < 1166057551; i++) {
        Tesla tesla = new Tesla();
        tesla.setId(i);
        tesla.setName("Semi Truck 202" + i);
        tesla.setFactory("弗拉蒙特特斯拉超级工厂");
        updateList.add(tesla);
    }
    List<Tesla> saveList =  new ArrayList<>();
    for (int i = 0; i < 2; i++) {
        Tesla tesla = new Tesla();
        tesla.setName("Semi Truck 202" + i);
        tesla.setFactory("柏林特斯拉超级工厂");
        saveList.add(tesla);
    }
    List<Tesla> saveOrUpdateList = new ArrayList<>();
    saveOrUpdateList.addAll(updateList);
    saveOrUpdateList.addAll(saveList);
    boolean b = teslaService.saveOrUpdateBatch(saveOrUpdateList);
    System.out.println("是否更新或者保存成功:" + b);
}
复制代码

执行该测试方法

image.png

对于设置了id的对象会限制性SELECT语句再执行UPDATE语句,并且只会更新给出的字段,对于没有设置id的对象会执行INSERT语句

IService 接口的 remove 相关方法

// 根据 ID 删除, 直接调用BaseMapper的deleteById()方法
default boolean removeById(Serializable id)
// 根据 columnMap 条件,删除记录,直接调用BaseMapper的deleteByMap()方法
default boolean removeByMap(Map<String, Object> columnMap) 
// 根据 entity 条件,删除记录,直接调用BaseMapper的remove()方法
default boolean remove(Wrapper<T> queryWrapper)
// 删除(根据ID 批量删除)
default boolean removeByIds(Collection<?> list) 
// 批量删除(jdbc批量提交)
default boolean removeBatchByIds(Collection<?> list)
// 批量删除(jdbc批量提交)
default boolean removeBatchByIds(Collection<?> list, int batchSize)
复制代码

在ITeslaServiceTest测试类中增加remove的测试方法

@Test
public void removeByMap(){
    Map<String, Object> map = new HashMap<>();
    map.put("id", 1166057551);
    map.put("name", "Cyber Truck 2029");
    boolean b = teslaService.removeByMap(map);
    System.out.println("是否删除成功:" + b);
}
复制代码

image.png

根据Map组成删除的Where子句执行删除操作

@Test
public void removeByIds(){
    List<Integer> idList = new ArrayList<>();
    idList.add(1166057563);
    idList.add(1166057562);
    idList.add(1166057561);
    boolean b = teslaService.removeByIds(idList);
    System.out.println("是否批量删除成功:" + b);
}
复制代码

image.png

批量删除成功

@Test
public void removeBatchByIds(){
    List<Integer> idList = new ArrayList<>();
    idList.add(1166057560);
    idList.add(1166057559);
    idList.add(1166057558);
    boolean b = teslaService.removeBatchByIds(idList);
    System.out.println("是否批量删除成功:" + b);
}
复制代码

image.png

与removeByIds()方法所调用删除语句不同

IService 接口的 update 相关方法

///根据 ID 选择修改,直接调用BaseMapper的updateById()方法
default boolean updateById(T entity);
// 根据 whereEntity 条件,更新记录,直接调用BaseMapper的update()方法,传入实体类
default boolean update(T entity, Wrapper<T> updateWrapper);
// 根据ID 批量更新
default boolean updateBatchById(Collection<T> entityList);
// TableId 注解存在更新记录,否插入一条记录
boolean saveOrUpdate(T entity);
复制代码

在ITeslaServiceTest测试类中增加update的测试方法

@Test
public void updateBatchById(){
    List<Tesla> updateList = new ArrayList<>();
    for (int i = 1166057556; i < 1166057560; i++) {
        Tesla tesla = new Tesla();
        tesla.setId(i);
        tesla.setFactory("柏林特斯拉超级工厂");
        updateList.add(tesla);
    }
    boolean b = teslaService.updateBatchById(updateList);
    System.out.println("是否更新成功:" + b);
}
复制代码

image.png

@Test
public void saveOrUpdate(){
    Tesla tesla = new Tesla();
    tesla.setName("Model S");
    tesla.setFactory("得克萨斯州特斯拉超级工厂");
    tesla.setPrice(880000.00);
    boolean b = teslaService.saveOrUpdate(tesla);
    System.out.println("保存或者更新成功:" + b);
}
复制代码

image.png

五、自定义 MPG 中的代码模板

MPG 根据模板生成 service 和 controller 代码, MPG的代码模板在 generator包下的templates文件夹下

image.png

默认提供的模板只能够生成XxxController类,并不包含任何方法,如果需要在XxxController类中生成增删改查方法就需要自定义controller模板。

image.png

使用 Spring 全家桶之 Spring Boot 2.6.4(四)- Data Access(Part D MyBatis Plus) 中的 spring-boot-mybatisplus项目,将controller代码模板拷贝至自己项目中的templates文件夹下,项目中使用的是freemarker模板引擎,所以拷贝ftl结尾的controller模板

在application.yml中增加freemarker模板引擎的配置

spring:
  freemarker:
    template-loader-path: classpath:/resources/templates
    suffix: .ftl
复制代码
package ${package.Controller};
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import java.util.List;
import org.springframework.web.bind.annotation.RestController;
import ${package.Entity}.${entity};
/**
 * @author ${author}
 * @since ${date}
 */
@RestController
@RequestMapping("/${table.entityPath}")
public class ${table.controllerName} {
     @Resource
     private ${table.serviceName} ${table.entityPath}Service;
     // 查询列表
     @GetMapping
     public List<${entity}> list(){
         return ${table.entityPath}Service.list();
     }
     // 根据id查询
     @GetMapping("/{id}")
     public ${entity} findOne(@PathVariable("id") Integer id){
         return ${table.entityPath}Service.getById(id);
     }
     // 更新或保存
     @PostMapping
     public Boolean save(@RequestBody ${entity} ${table.entityPath}){
         return ${table.entityPath}Service.saveOrUpdate(${table.entityPath});
     }
     // 根据id删除
     @DeleteMapping("/{id}")
     public Boolean removeById(@PathVariable("id") Integer id){
         return ${table.entityPath}Service.removeById(id);
     }
     // 查询总记录数
     @GetMapping("/count")
     public Long count(){
         return ${table.entityPath}Service.count();
     }
     // 批量删除
     @PostMapping("/delete")
     public Boolean batchDelete(@RequestBody List<Integer> ids){
         return ${table.entityPath}Service.removeBatchByIds(ids);
     }
     // 批量更新或者保存
     @PostMapping("/batch")
     public Boolean saveOrUpdateBatch(List<${entity}> ${table.entityPath}List){
         return ${table.entityPath}Service.saveOrUpdateBatch(${table.entityPath}List);
     }
     // 分页查询
     @GetMapping("/page")
     public Page<${entity}> findPage(@RequestParam("pageNum") Integer pageNum,
                                     @RequestParam("pageSize") Integer pageSize){
         Page<${entity}> page = new Page<>(pageNum, pageSize);
         QueryWrapper<${entity}> queryWrapper = new QueryWrapper<>();
         userService.page(page, queryWrapper);
         return page;
     }
}
复制代码

代码模板中

  • ${entity}:实体类类名,如User
  • ${table.entityPath}:实体类类名小写,user
  • ${table.serviceName}:Service接口名,IUserService
  • ${table.controllerName}:Controller类类名,UserController

将mybatis-plus-mpg中的代码生成器GeneratorApp拷贝至spring-boot-mybatisplus的test目录下,运行代码生成器

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;
    // 查询列表
    @GetMapping
    public List<User> list(){
    return userService.list();
    }
    // 根据id查询
    @GetMapping("/{id}")
    public User findOne(@PathVariable("id") Integer id){
        return userService.getById(id);
    }
    // 更新或保存
    @PostMapping
    public Boolean save(@RequestBody User user){
        return userService.saveOrUpdate(user);
    }
    // 根据id删除
    @DeleteMapping("/{id}")
    public Boolean removeById(@PathVariable("id") Integer id){
        return userService.removeById(id);
    }
    // 查询总记录数
    @GetMapping("/count")
    public Long count(){
        return userService.count();
    }
    // 批量删除
    @PostMapping("/delete")
    public Boolean batchDelete(@RequestBody List<Integer> ids){
        return userService.removeBatchByIds(ids);
    }
    // 批量更新或者保存
    @PostMapping("/batch")
    public Boolean saveOrUpdateBatch(List<User> userList){
        return userService.saveOrUpdateBatch(userList);
    }
    // 分页查询
    @GetMapping("/page")
    public Page<User> findPage(@RequestParam("pageNum") Integer pageNum,
                                    @RequestParam("pageSize") Integer pageSize){
        Page<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        userService.page(page, queryWrapper);
        return page;
    }
}
复制代码

启动SpringBoot项目,测试生成的代码

查询用户列表 /user

image.png

根据id查询用户 /user/1

image.png

更新或者保存用户 /user

image.png

查询用户总数 /user/count

image.png

根据id删除用户 /user/1

image.png

分页查询用户 /user/page?pageNum=2&pageSize=3

image.png

批量删除 /user/delete

image.png

相关文章
|
1月前
|
Java 关系型数据库 数据库连接
MyBatis Plus 解决大数据量查询慢问题
MyBatis Plus 解决大数据量查询慢问题
|
1月前
|
druid Java 数据库连接
Spring Boot3整合MyBatis Plus
Spring Boot3整合MyBatis Plus
39 1
|
21天前
|
Java 数据库连接 mybatis
mybatis plus字段为null或空字符串把原来的数据也更新了,只需要注解
mybatis plus字段为null或空字符串把原来的数据也更新了,只需要注解
16 0
|
22天前
|
JavaScript Java 关系型数据库
SpringBoot + Mybatis + Vue的代码生成器
SpringBoot + Mybatis + Vue的代码生成器
32 2
|
30天前
|
Java 数据库连接 数据库
Spring Boot整合MyBatis Plus集成多数据源轻松实现数据读写分离
Spring Boot整合MyBatis Plus集成多数据源轻松实现数据读写分离
26 2
|
1月前
|
存储 缓存 Java
什么!?实战项目竟然撞到阿里面试的原题!???关于MyBatis Plus的缓存机制
什么!?实战项目竟然撞到阿里面试的原题!???关于MyBatis Plus的缓存机制
|
1月前
|
缓存 Java 数据库连接
MyBatis Plus的“幻查” 规范到底要怎样使用哪几个查询函数 为什么会出现幻查?还有幻删为什么会删不掉
MyBatis Plus的“幻查” 规范到底要怎样使用哪几个查询函数 为什么会出现幻查?还有幻删为什么会删不掉
|
3月前
|
SQL Java 数据库连接
快速上手MyBatis Plus:简化CRUD操作,提高开发效率!
快速上手MyBatis Plus:简化CRUD操作,提高开发效率!
|
29天前
|
SQL Java 数据库连接
挺详细的spring+springmvc+mybatis配置整合|含源代码
挺详细的spring+springmvc+mybatis配置整合|含源代码
35 1
|
3月前
|
Java 数据库连接 Maven
SSM框架整合:掌握Spring+Spring MVC+MyBatis的完美结合!
SSM框架整合:掌握Spring+Spring MVC+MyBatis的完美结合!