正在连接海拉鲁...

MyBatis-plus

概述

是一个Mybatis的增强工具,在Mybatis的基础上只做增强,不做改变。目的就是简化Mybatis的操作

使用

  1. 添加依赖

    <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>3.5.3</version>
            </dependency>
  2. 数据源配置

    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
    spring.datasource.username=root
    spring.datasource.password=root
    ###日志配置设置
    mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
    
    # mapper存储位置配置
    mybatis-plus.mapper-locations=classpath:/mapper/**/*.xml
  3. 实体类

    @Data
    @TableName("dept")
    public class Dept {
        @TableId
        private Integer deptno;
        private String dname;
        private String loc;
    }
  4. mapper接口

    public interface DeptMapper extends BaseMapper<Dept> {
    
    }
  5. 测试

    @SpringBootTest
    class MybatisplusDemoApplicationTests {
        @Autowired
        private DeptMapper deptMapper;
        @Test
        public void testGetById(){
            Dept dept = deptMapper.selectById(10);
            System.out.println(dept);
        }
        @Test
        public void getAll(){
            QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
            List<Dept> list = deptMapper.selectList(queryWrapper);
            System.out.println(list);
        }
    
        @Test
        public void getDepts(){
            QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
            queryWrapper
                    .in("deptno",30,40,50)
    //                .ge("deptno",50)
    //                .eq("dname","hr")
    //                .like("loc","s")
                                        ;
            List<Dept> list = deptMapper.selectList(queryWrapper);
            System.out.println(list);
        }
    
        @Test
        public void testInsert(){
            int i = deptMapper.insert(new Dept(null, "销售部", "北京"));
            System.out.println(i);
        }
    
        @Test
        public void testUpdate(){
            Dept dept = new Dept(105, "销售部", "上海");
            int i = deptMapper.updateById(dept);
            System.out.println(i);
        }
    }

实体关联

  1. 修改实体类

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @TableName("emp")
    public class Emp {
        @TableId(type = IdType.AUTO)
        private Integer empno;
        private String ename;
        private String job;
        private Date hiredate;
        private Double sal;
        private Integer mgr;
        private Double comm;
        private Integer deptno;
        @TableField(exist = false)
        private Dept dept;
    
    }
  2. 编写mapper接口

    public interface EmpMapper extends BaseMapper<Emp> {
        @Override
        @ResultMap("baseMap")
        @Select("select * from emp where empno = #{empno}")
        Emp selectById(Serializable id);
    }
  3. 编写mapper.xml

    //mapper/EmpMapper.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.neu.mybatisplus_demo.mapper.EmpMapper">
        <resultMap id="baseMap" type="com.neu.mybatisplus_demo.entity.Emp">
            <association property="dept" column="deptno" select="com.neu.mybatisplus_demo.mapper.DeptMapper.selectById"></association>
        </resultMap>
    </mapper>
  4. 修改application.properties

    # mapper存储位置配置
    mybatis-plus.mapper-locations=classpath:/mapper/**/*.xml

分页

  1. 添加一个分页插件拦截器

    @Configuration
    public class MybatisplusConfig {
    
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor(){
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
            return interceptor;
        }
    }
  2. 测试

    @Test
        public void testPage(){
            Page<Dept> deptPage = new Page<>(2,3);
            QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
            Page<Dept> deptPage1 = deptMapper.selectPage(deptPage, queryWrapper);
            System.out.println(deptPage1.getRecords());//当前页数据
            System.out.println(deptPage1.getTotal());//总行数
            System.out.println(deptPage1.getPages());//总页数
        }

业务逻辑层

  1. 接口

    public interface DeptService extends IService<Dept> {
    }
  2. 实现类

    @Service
    public class DeptServiceImpl extends ServiceImpl<DeptMapper,Dept> implements DeptService {
    
    }
  3. 测试

    @Autowired
    private DeptService deptService;
       
    @Test
    public void deptServiceGetById(){
        Dept byId = deptService.getById(10);
        System.out.println(byId);
    }
       
    @Test
    public void deptServiceGetAll(){
        List<Dept> list = deptService.list();
        System.out.println(list);
    }
       
    @Test
    public void deptServiceGetByPaged(){
        Page<Dept> page = deptService.page(new Page<>(2, 5), new QueryWrapper<>());
        System.out.println(page);
        System.out.println(page.getRecords());
        System.out.println(page.getTotal());
        System.out.println(page.getPages());
    }
    @Test
    public void deptServiceInsert(){
        boolean b = deptService.save(new Dept(null, "鱼长梦短", "IGXE"));
        System.out.println(b);
    }
       
    @Test
    public void deptServiceUpdate(){
        boolean b = deptService.updateById(new Dept(106, "元女王", "IGXE"));
        System.out.println(b);
    }
       
    @Test
    public void deptServiceDelete(){
        boolean b = deptService.removeById(106);
        System.out.println(b);
    }

控制器代码生成

  1. 添加依赖

    <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-generator</artifactId>
                <version>3.5.3</version>
            </dependency>
    
            <!-- Velocity 模板引擎,用于生成代码 -->
            <dependency>
                <groupId>org.apache.velocity</groupId>
                <artifactId>velocity-engine-core</artifactId>
                <version>2.3</version>
            </dependency>
  2. 添加模板

    package ${package.Controller};
    
    import ${package.Entity}.${entity};
    import ${package.Service}.${entity}Service;
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.List;
    
    @RestController
    @RequestMapping("/api/${entity}")
    public class ${entity}Controller {
    
        private ${entity}Service ${entity.toLowerCase()}Service;
    
        @Autowired
        public void set${entity}Service(${entity}Service ${entity.toLowerCase()}Service) {
            this.${entity.toLowerCase()}Service = ${entity.toLowerCase()}Service;
        }
    
        // 创建(Create)
        @PostMapping("/create")
        public String create(@RequestBody ${entity} ${entity.toLowerCase()}) {
                ${entity.toLowerCase()}Service.save(${entity.toLowerCase()});
            return "Created successfully";
        }
    
        // 读取(Read)
        @GetMapping("/get/{id}")
        public ${entity} getById(@PathVariable Long id) {
            return ${entity.toLowerCase()}Service.getById(id);
        }
    
        // 查询全部(Read All)
        @GetMapping("/getAll")
        public List<${entity}> getAll() {
            return ${entity.toLowerCase()}Service.list();
        }
    
        // 更新(Update)
        @PutMapping("/update")
        public String update(@RequestBody ${entity} ${entity.toLowerCase()}) {
                ${entity.toLowerCase()}Service.updateById(${entity.toLowerCase()});
            return "Updated successfully";
        }
    
        // 删除(Delete)
        @DeleteMapping("/delete/{id}")
        public String delete(@PathVariable Long id) {
                ${entity.toLowerCase()}Service.removeById(id);
            return "Deleted successfully";
        }
    
        // 分页查询(Pagination)
        @GetMapping("/page")
        public Page<${entity}> list(@RequestParam(defaultValue = "1") int current, @RequestParam(defaultValue = "10") int size) {
            return ${entity.toLowerCase()}Service.page(new Page<>(current, size));
        }
    }

逻辑删除

  1. 修改实体类

    @Getter
    @Setter
    @TableName("sysuser")
    public class SysUser implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        @TableId(value = "id", type = IdType.AUTO)
        private Integer id;
    
        private String username;
    
        private String password;
    
        //@TableLogic(value="0",delval="1")
        @TableLogic
        private Integer status;
    }

设置mybatis延迟加载

# 设置延迟加载
mybatis.configuration.lazy-loading-enabled=true
# 取消积极加载
mybatis.configuration.aggressive-lazy-loading=false

取消下划线到驼峰的命名转换

mybatis-plus.configuration.map-underscore-to-camel-case=false