首页 > 其他分享 >最近正在集成SpringBoot与MyBatis-plus,体验感很好啊

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

时间:2023-09-28 11:44:19浏览次数:49  
标签:cn SpringBoot boot Class plus MyBatis import id highedu

image

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='班级信息表';

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='老师信息表';
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 {
}
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());//下一页
    }
}

多表操作

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 {
}

标签:cn,SpringBoot,boot,Class,plus,MyBatis,import,id,highedu
From: https://www.cnblogs.com/fcloud/p/17734798.html

相关文章

  • 下载vue.js、element-plus的js和样式、locale.js、icon-vue.js
    一、下载vue.js地址:https://www.bootcdn.cn/vue/找到vue.global.js点击复制链接,在浏览器中打开,如下所示:二、下载element-plus的js和样式进入element-plus的官网:https://element-plus.org/zh-CN/点击指南点击安装1、下载样式:复制//unpkg.com/element-plus/dist/inde......
  • 实战指南,SpringBoot + Mybatis 如何对接多数据源
    本文分享自华为云社区 《实战指南,SpringBoot+Mybatis如何对接多数据源》,作者:战斧。在我们开发一些具有综合功能的项目时,往往会碰到一种情况,需要同时连接多个数据库,这个时候就需要用到多数据源的设计。而Spring与Myabtis其实做了多数据源的适配,只需少许改动即可对接多数据源。......
  • Mybatis中的设计模式
    最近在看《通用源码阅读指导书:Mybatis源码详解》,这本书一一介绍了Mybatis中的各个包的功能,同时也涉及讲了一些阅读源码的技巧,还讲了一些源码中涉及的设计模式,这是本篇文章介绍的内容在多说一点这本书,Mybatis是大部分Java开发者都熟悉的一个框架,通过这本书去学习如何阅读源码非常......
  • SpringBoot实现文件上传的多种方式
    我们平时在项目开发过程中,会遇到许多的文件上传与下载的需求,今天我们就来梳理一下文件上传的代码实现,基于SpringBoot快速搭建服务,集成文件上传功能,包括传统的文件上传方式,也拓展OSS对象存储方式。项目类型是Maven项目一、引入web依赖<dependency><groupId>org.springframework......
  • Web-入门-SpringBoot快速入门 创建springboot web项目
    web入门spring官网spring发展到今天已经形成了一种开发生态圈,spring提供了若干个子项目,为每个项目用于完成特定的功能。这些框架都是基于一个基础框架:直接基于SpringFramework基础框架进行开发会有两大难题:1.配置繁琐。2.入门难度大。所以spring家族意识到了这一点,......
  • 使用SpringBoot开发一个POST接口
    SpringBoot项目的分层SpringBoot框架项目一般分为五层:View层:向用户展示页面Controller层:前后端交互层,接收前端请求,调用Service层中的方法,接收Service层返回的数据并将其返回到前端。Service层:存放业务处理的逻辑,以及一些操作数据库的接口Mapper层:也可以成为DAO层,是数......
  • 在deepin上使用Fleet开发SpringBoot 3.0.0项目
    前言Fleet被称为是由JetBrains打造的下一代IDE,目前出于公测状态,可以免费下载使用。SpringBoot3.0.0最小支持是JDK17,这或许是对于JDK8的断舍离迈出的重大一步。出于对新工具和新技术的好奇,我开始尝试在deepin上用Fleet开发一个SpringBoot3.0.0项目,继续我的SpringBoot学习......
  • SpringBoot启动报错
    问题描述按照以往的代码进行SpringBoot的相应部署,但是爆出来这个错误:问题解决里面说找不到我定义的bean实体类,那就加上这么一条注解,让他能够找到实体类:然后启动:并在浏览器里面查看一下:ok!问题解决!......
  • springboot分层解耦
    软件开发需要符合“高内聚低耦合”的特性,所以需要将程序分为三层即: 使每一层各司其职,增加软件的复用性,使其更加便于维护,利于扩展。controller层:packagecom.wmx.controller;importcom.wmx.dao.EmpDao;importcom.wmx.dao.impl.EmpDaoA;importcom.wmx.pojo.Emp;impo......
  • SpringBoot学习4(02整合项目+前端)
    1.添加web界面在resources包下的static包中导入需要用的包,编写html。 1.1测试一下 页面控制台中成功获取数据 1.2页面显示:查询全部信息 1.3添加功能实现 新建按钮的点击事件为   @click="handleCreate()"点击新建后弹出添加页面,该页面的确定提交按钮点击事......