最近正在集成SpringBoot与MyBatis-plus,体验感很好啊

sql

CREATE TABLE `class` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '编号',
  `name` varchar(30) DEFAULT NULL COMMENT '班级名',
  `floor` int(3) DEFAULT NULL COMMENT '楼层',
  `teacher_id` int(11) DEFAULT NULL COMMENT '老师编号(FK)',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='班级信息表';
INSERT INTO `class` VALUES ('1', '1年级2班', '4', '2');
INSERT INTO `class` VALUES ('2', '1年级3班', '4', '2');
INSERT INTO `class` VALUES ('3', '2年级1班', '1', '4');
INSERT INTO `class` VALUES ('4', '2年级2班', '2', '5');
INSERT INTO `class` VALUES ('5', '2年级3班', '3', '6');
INSERT INTO `class` VALUES ('6', '3年级1班', '4', '7');
INSERT INTO `class` VALUES ('7', '3年级2班', '1', '8');
INSERT INTO `class` VALUES ('8', '3年级3班', '2', '9');
INSERT INTO `class` VALUES ('9', '4年级1班', '3', '10');
INSERT INTO `class` VALUES ('10', '4年级2班', '4', '11');
INSERT INTO `class` VALUES ('11', '4年级3班', '1', '12');
INSERT INTO `class` VALUES ('12', '5年级1班', '2', '13');
INSERT INTO `class` VALUES ('13', '5年级3班', '4', '15');
INSERT INTO `class` VALUES ('14', '6年级2班', '2', '17');
INSERT INTO `class` VALUES ('15', '6年级3班', '3', '18');
INSERT INTO `class` VALUES ('16', '1年级4班', '4', '99');
INSERT INTO `class` VALUES ('17', '2年级4班', '2', '99');
INSERT INTO `class` VALUES ('18', '3年级4班', '1', '99');
INSERT INTO `class` VALUES ('19', '4年级1班', '1', '20');
INSERT INTO `class` VALUES ('30', '4年级1班', '22', '20');

CREATE TABLE `teacher` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '编号',
  `name` varchar(30) DEFAULT NULL COMMENT '名字',
  `age` int(2) DEFAULT NULL COMMENT '年龄',
  `title` varchar(30) DEFAULT NULL COMMENT '职称',
  `manager` int(11) DEFAULT NULL COMMENT '上司编号(FK)',
  `salary` int(6) DEFAULT NULL COMMENT '工资',
  `comm` int(6) DEFAULT NULL COMMENT '奖金',
  `gender` char(1) DEFAULT NULL COMMENT '性别',
  `subject_id` int(11) DEFAULT NULL COMMENT '科目编号(FK)',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='老师信息表';
INSERT INTO `teacher` VALUES ('1', '刘苍松', '55', '总监', '20', '10000', '5000', '男', '1');
INSERT INTO `teacher` VALUES ('2', '范传奇', '33', '三级讲师', '1', '3000', null, '男', '2');
INSERT INTO `teacher` VALUES ('3', '王克晶', '32', '一级讲师', '1', '8000', '3000', '女', '3');
INSERT INTO `teacher` VALUES ('4', '刘国斌', '29', '二级讲师', '1', '7300', '3400', '男', '4');
INSERT INTO `teacher` VALUES ('5', '成恒', '35', '三级讲师', '1', '5200', '4600', '男', '5');
INSERT INTO `teacher` VALUES ('6', '张皓岚', '33', '二级讲师', '1', '7800', '700', '男', '2');
INSERT INTO `teacher` VALUES ('7', '胡悦', '25', '一级讲师', '1', '9000', '2800', '女', '1');
INSERT INTO `teacher` VALUES ('8', '齐雷', '45', '总监', '20', '9800', '7800', '男', '3');
INSERT INTO `teacher` VALUES ('9', '王海涛', '44', '二级讲师', '8', '3100', '1200', '男', '4');
INSERT INTO `teacher` VALUES ('10', '张久军', '39', '一级讲师', '8', '2000', '6000', '男', '5');
INSERT INTO `teacher` VALUES ('11', '于健', '27', '二级讲师', '12', '3800', null, '男', '2');
INSERT INTO `teacher` VALUES ('12', '张立志', '34', '总监', '20', '13000', '900', '男', '3');
INSERT INTO `teacher` VALUES ('13', '吴华', '46', '总监', '20', '8700', '6900', '男', '5');
INSERT INTO `teacher` VALUES ('14', '李大帅', '29', '三级讲师', '13', '7000', null, '男', '1');
INSERT INTO `teacher` VALUES ('15', '田浩', '26', '二级讲师', '13', '5600', '1900', '男', '4');
INSERT INTO `teacher` VALUES ('16', '肖旭伟', '36', '一级讲师', '12', '6800', '600', '男', '2');
INSERT INTO `teacher` VALUES ('17', '张敏', '29', '三级讲师', '13', '6100', '400', '女', '3');
INSERT INTO `teacher` VALUES ('18', '赵微', '26', '二级讲师', '13', '4600', '6500', '女', '4');
INSERT INTO `teacher` VALUES ('19', '李源', '25', '三级讲师', '13', '6300', '0', '男', '4');
INSERT INTO `teacher` VALUES ('20', '韩少云', '55', '老板', null, '1', '0', '男', null);

pom.xml

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
		<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
		<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3</version>
        </dependency>

application.yml

spring:
  # 数据库连接配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/hedu?useSSL=false&serverTimeZone=Asia/Shanghai
    username: root
    password: root
# mybatis-plus配置
mybatis-plus:
  mapper-locations: classpath:mappers/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

Mybatis-plus的分页插件的配置

package cn.highedu.boot.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class MybatisPlusConfig {
    /**
     * 分页插件的配置
     * @return
     */
    @Bean
    public MybatisPlusInterceptor paginationInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        /**
         * DbType.XXX
         * XXX 为具体的数据库类型如MYSQL,ORACLE
         */
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

创建基本类

Class

package cn.highedu.boot.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Class {
    @TableId(type = IdType.AUTO)
    private Integer id;
    private String name;
    private Integer floor;
    private Integer teacherId;
}

ClassMapper

package cn.highedu.boot.mapper;

import cn.highedu.boot.entity.Class;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;

@Mapper
public interface ClassMapper extends BaseMapper<Class> {
}

ClassService

package cn.highedu.boot.service;

import cn.highedu.boot.entity.Class;
import com.baomidou.mybatisplus.extension.service.IService;

public interface ClassService extends IService<Class> {
}

ClassServiceImpl

package cn.highedu.boot.service.impl;

import cn.highedu.boot.entity.Class;
import cn.highedu.boot.mapper.ClassMapper;
import cn.highedu.boot.service.ClassService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

@Service
public class ClassServiceImpl extends ServiceImpl<ClassMapper, Class> implements ClassService {
}

teacher

package cn.highedu.boot.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
    private Integer id;
    private String name;
    private Integer age;
    private String title;
    private Integer manager;
    private Integer salary;
    private Integer comm;
    private Character gender;
    private Integer subjectId;
}

TeacherMapper

package cn.highedu.boot.mapper;

import cn.highedu.boot.entity.Teacher;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;

@Mapper
public interface TeacherMapper extends BaseMapper<Teacher> {
}

TeacherService

package cn.highedu.boot.service;

import cn.highedu.boot.entity.Teacher;
import com.baomidou.mybatisplus.extension.service.IService;

public interface TeacherService extends IService<Teacher> {
}

TeacherServiceImpl

package cn.highedu.boot.service.impl;

import cn.highedu.boot.entity.Teacher;
import cn.highedu.boot.mapper.TeacherMapper;
import cn.highedu.boot.service.TeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {
}

单表操作

SingleTableOperationTest

package cn.highedu.boot.service;

import cn.highedu.boot.entity.Class;
import cn.highedu.boot.mapper.ClassMapper;
import cn.highedu.boot.service.impl.ClassServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class ClassServiceTest  extends ClassServiceImpl {

    @Autowired
    private ClassMapper classMapperSimple;

    //基本操作
    //insert
    /**
     * 新增一条记录
     */
    @Test
    void simpleAddOne(){
        Class addOneClazz = new Class();
        addOneClazz.setName("4年级1班");
        addOneClazz.setFloor(22);
        addOneClazz.setTeacherId(20);
        //INSERT INTO class ( name, floor, teacher_id ) VALUES ( ?, ?, ? )
        int addOneResult = classMapperSimple.insert(addOneClazz);
        System.out.println(addOneResult);
    }

    //delete
    /**
     * 根据Id删除一条记录
     */
    @Test
    void simpleDeleteOneById(){
        //DELETE FROM class WHERE id=?
        int deleteByIdResult = classMapperSimple.deleteById(1);
        System.out.println(deleteByIdResult);
    }

    //update
    /**
     * 根据Id更改一条记录
     */
    @Test
    void simpleUpdateOneById(){
        Class updateClass = new Class();
        updateClass.setId(2);
        updateClass.setName("1年级3班");
        updateClass.setFloor(4);
        updateClass.setTeacherId(2);
        //UPDATE class SET name=?, floor=?, teacher_id=? WHERE id=?
        int updateByIdResult = classMapperSimple.updateById(updateClass);
        System.out.println(updateByIdResult);
    }

    //select
    /**
     * 根据Id查询一条记录
     */
    @Test
    void simpleQueryOneById(){
        //SELECT id,name,floor,teacher_id FROM class WHERE id=?
        Class queryOneClass = classMapperSimple.selectById(1);
        System.out.println(queryOneClass);
    }

    /**
     * 查询所有记录
     */
    @Test
    void simpleQueryAll() {
        //SELECT id,name,floor,teacher_id FROM class
        List<Class> queryClasses = classMapperSimple.selectList(null);
        System.out.println(queryClasses);
    }


    /**
     *|     函数名   |     说明     |
     *| ----------- | ----------- |
     *|      eq     |     等于     |
     *|      ne     |     不等     |
     *|      gt     |     大于     |
     *|      it     |     小于     |
     *|    between  | 在值1到值2之间 |
     *|     like    |   模糊查询    |
     *|     isNull  |  字段为NULL   |
     */

    @Autowired
    private ClassMapper classMapperComplex;

    //进阶操作

    //单表操作
    //select
    /**
     * 根据Id查询条数据
     */
    @Test
    void complexQueryOne(){
        LambdaQueryWrapper<Class> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Class::getId, 1);
        //SELECT id,name,floor,teacher_id FROM class WHERE (id = ?);
        Class complexQueryOne = classMapperComplex.selectOne(queryWrapper);
        System.out.println(complexQueryOne);
    }
    /**
     * 查询相同条件的数据
     */
    @Test
    void complexQueryAll(){
        LambdaQueryWrapper<Class> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Class::getFloor,1);
        //SELECT id,name,floor,teacher_id FROM class WHERE (floor = ?);
        List<Class> complexQueryAll = classMapperComplex.selectList(queryWrapper);
        System.out.println(complexQueryAll);
    }

    /**
     * 查询范围内的数据
     */
    @Test
    void complexBetweenQuery(){
        LambdaQueryWrapper<Class> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.between(Class::getFloor,1,3);
        //SELECT id,name,floor,teacher_id FROM class WHERE (floor BETWEEN ? AND ?);
        List<Class> complexQueryAll = classMapperComplex.selectList(queryWrapper);
        System.out.println(complexQueryAll);
    }

    /**
     * 模糊查询
     * like():前后加百分号,如 %1年级%
     * likeLeft():前面加百分号,如 %1年级
     * likeRight():后面加百分号,如 1年级%
     */
    @Test
    void complexLikeQuery(){
        LambdaQueryWrapper<Class> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.likeRight(Class::getName,"1年级");
        // SELECT id,name,floor,teacher_id FROM class WHERE (name LIKE ?);
        List<Class> complexLikeQuery = classMapperComplex.selectList(queryWrapper);
        System.out.println(complexLikeQuery);
    }

    /**
     * 按照楼层升序排列,从小到大
     */
    @Test
    void complexOrderQuery(){
        LambdaQueryWrapper<Class> queryWrapper = Wrappers.lambdaQuery();
        //condition :条件,返回boolean,当condition为true,进行排序,如果为false,则不排序
        //isAsc:是否为升序,true为升序,false为降序
        //columns:需要操作的列
        queryWrapper.orderBy(true,true,Class::getFloor);
        List<Class> complexOrderByAscQuery= classMapperComplex.selectList(queryWrapper);
        System.out.println(complexOrderByAscQuery);
    }
    /**
     * 分页查询
     */
    @Test
    void complexPageQuery(){
        Page<Class> page = new Page<>(1,3);
        classMapperComplex.selectPage(page, null);
        System.out.println(page.getRecords());//每页数据list集合


        System.out.println(page.getCurrent());//当前页
        System.out.println(page.getSize());//每页显示记录数
        System.out.println(page.getTotal());//总记录数
        System.out.println(page.getPages());//总页数

        System.out.println(page.hasPrevious());//上一页
        System.out.println(page.hasNext());//下一页
    }
}

多表操作

MultipleTableOperationTest


热门相关:我有一座冒险屋   重生之女将星   我成了暴戾帝君的小娇包   楚氏赘婿   紫府仙缘