SpringBoot(十四)整合MyBatis

2023-05-16

官方文档:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

Maven仓库地址:https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter/2.1.1

在这里插入图片描述

整合测试

1、导入 MyBatis 所需要的依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>

2、配置数据库连接信息(不变)

spring:
  datasource:
    username: root
    password: 123456
    #?serverTimezone=UTC解决时区的报错
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    #Spring Boot 默认是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
    #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

3、测试数据库是否连接成功!

4、创建实体类,导入 Lombok!

Department.java

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Department {

    private Integer id;
    private String departmentName;

}

5、创建mapper目录以及对应的 Mapper 接口

DepartmentMapper.java

//@Mapper : 表示本类是一个 MyBatis 的 Mapper
@Mapper
@Repository
public interface DepartmentMapper {

    // 获取所有部门信息
    List<Department> getDepartments();

    // 通过id获得部门
    Department getDepartment(Integer id);

}

6、对应的Mapper映射文件

DepartmentMapper.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.kuang.mapper.DepartmentMapper">

    <select id="getDepartments" resultType="Department">
       select * from department;
    </select>

    <select id="getDepartment" resultType="Department" parameterType="int">
       select * from department where id = #{id};
    </select>

</mapper>

注意配置文件中如果使用别名,需要在 yml 文件中配置,这里还有指定 xxxMapper.xml 的位置

# 整合mybatis
mybatis:
  type-aliases-package: com.kuang.pojo
  mapper-locations: classpath:mybatis/mapper/*.xml

7、maven配置资源过滤问题

<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
    </resource>
</resources>

8、编写部门的 DepartmentController 进行测试!

@RestController
public class DepartmentController {
    
    @Autowired
    DepartmentMapper departmentMapper;
    
    // 查询全部部门
    @GetMapping("/getDepartments")
    public List<Department> getDepartments(){
        return departmentMapper.getDepartments();
    }

    // 查询全部部门
    @GetMapping("/getDepartment/{id}")
    public Department getDepartment(@PathVariable("id") Integer id){
        return departmentMapper.getDepartment(id);
    }
    
}

启动项目访问进行测试!

我们增加一个员工类再测试下,为之后做准备

1、新建一个pojo类 Employee ;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {

    private Integer id;
    private String lastName;
    private String email;
    //1 male, 0 female
    private Integer gender;
    private Integer department;
    private Date birth;

    private Department eDepartment; // 冗余设计

}

2、新建一个 EmployeeMapper 接口

//@Mapper : 表示本类是一个 MyBatis 的 Mapper
@Mapper
@Repository
public interface EmployeeMapper {

    // 获取所有员工信息
    List<Employee> getEmployees();

    // 新增一个员工
    int save(Employee employee);

    // 通过id获得员工信息
    Employee get(Integer id);

    // 通过id删除员工
    int delete(Integer id);

}

3、编写 EmployeeMapper.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.kuang.mapper.EmployeeMapper">

    <resultMap id="EmployeeMap" type="Employee">
        <id property="id" column="eid"/>
        <result property="lastName" column="last_name"/>
        <result property="email" column="email"/>
        <result property="gender" column="gender"/>
        <result property="birth" column="birth"/>
        <association property="eDepartment"  javaType="Department">
            <id property="id" column="did"/>
            <result property="departmentName" column="dname"/>
        </association>
    </resultMap>

    <select id="getEmployees" resultMap="EmployeeMap">
        select e.id as eid,last_name,email,gender,birth,d.id as did,d.department_name as dname
        from department d,employee e
        where d.id = e.department
    </select>

    <insert id="save" parameterType="Employee">
        insert into employee (last_name,email,gender,department,birth)
        values (#{lastName},#{email},#{gender},#{department},#{birth});
    </insert>

    <select id="get" resultType="Employee">
        select * from employee where id = #{id}
    </select>

    <delete id="delete" parameterType="int">
        delete from employee where id = #{id}
    </delete>

</mapper>

4、编写EmployeeController类进行测试

@RestController
public class EmployeeController {

    @Autowired
    EmployeeMapper employeeMapper;

    // 获取所有员工信息
    @GetMapping("/getEmployees")
    public List<Employee> getEmployees(){
        return employeeMapper.getEmployees();
    }

    @GetMapping("/save")
    public int save(){
        Employee employee = new Employee();
        employee.setLastName("zhangsan");
        employee.setEmail("zhangsan@qq.com");
        employee.setGender(1);
        employee.setDepartment(101);
        employee.setBirth(new Date());
        return employeeMapper.save(employee);
    }

    // 通过id获得员工信息
    @GetMapping("/get/{id}")
    public Employee get(@PathVariable("id") Integer id){
        return employeeMapper.get(id);
    }

    // 通过id删除员工
    @GetMapping("/delete/{id}")
    public int delete(@PathVariable("id") Integer id){
        return employeeMapper.delete(id);
    }

}

测试结果完成,搞定收工!


如果有收获!!! 希望老铁们来个三连,点赞、收藏、转发。
创作不易,别忘点个赞,可以让更多的人看到这篇文章,顺便鼓励我写出更好的博客
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringBoot(十四)整合MyBatis 的相关文章

随机推荐

  • 为什么要搭建自己的博客

    为什么要搭建自己的博客 xff1f 很多小伙伴起初和我有一样的疑惑 搭建博客的原因如下 现在市面上的博客很多 xff0c 比如如CSDN xff0c 博客园 xff0c 简书等平台 xff0c 可以直接在上面发表 xff0c 用户交互做的好
  • 为什么要写博客

    为什么要写博客 xff1f 我相信很多小伙伴和我有一样的疑惑 最近我也常和身边的朋友说写写博客做总结 xff0c 因为有的时候面试官遇到技术还不错的面试者会问你有没有博客 xff0c 如果有的话会在面试的时候额外加分 据我观察几乎每一个程序
  • hexo搭建博客【详细步骤】适合初学者

    为什么要搭建自己的博客 xff1a https blog csdn net weixin 45606067 article details 107966915 下面说一下如何从零开始上手搭建博客 Hexo搭建博客步骤 xff1a 搭建博客需
  • SpringBoot(一)概述、HelloWord案例

    1 SpringBoot 简介 回顾什么是Spring Spring是一个开源框架 xff0c 2003 年兴起的一个轻量级的Java 开发框架 Spring是为了解决企业级应用开发的复杂性而创建的 xff0c 简化开发 Spring是如何
  • PyTorch:view() 与 reshape() 区别详解

    总之 xff0c 两者都是用来重塑tensor的shape的 view只适合对满足连续性条件 xff08 contiguous xff09 的tensor进行操作 xff0c 而reshape同时还可以对不满足连续性条件的tensor进行操
  • SpringBoot(二)运行原理探究

    我们之前写的HelloSpringBoot xff0c 到底是怎么运行的呢 xff0c Maven项目 xff0c 我们一般从 pom xml文件探究起 SpringBoot2 3 3版本的官网文档说明 xff1a https docs s
  • idea查看源码时总是出现 .class而不是 .java源码

    步骤 1 File gt Settings gt Maven gt importing xff08 勾选上 Sources 和 Documentation xff09 2 右键项目的pom xml gt Maven gt Reimport
  • SpringBoot(三)yaml配置注入

    配置文件 SpringBoot使用一个全局的配置文件 xff0c 配置文件名称是固定的 application properties 语法结构 xff1a key 61 value application yml 语法结构 xff1a ke
  • SpringBoot(四)JSR303数据校验及多环境切换

    1 JSR303数据校验 先看看如何使用 Springboot 中可以用 64 validated 来校验数据 xff0c 如果数据异常则会统一抛出异常 xff0c 方便异常中心统一处理 我们这里来写个注解让我们的 name 只能支持 Em
  • SpringBoot(五)自动配置原理

    1 配置文件到底能写什么 xff1f 怎么写 xff1f SpringBoot 官网有大量的配置说明 xff0c 我们是无法全部记住的 xff1b SpringBoot 2 3 3 官网文档 2 分析自动配置原理 这里我们以 HttpEnc
  • SpringBoot(六)日志处理

    1 日志框架 简单分析案例 xff1a 小张 xff1b 开发一个大型系统 xff1b 1 System out println 34 34 xff1b 将关键数据打印在控制台 xff1b 去掉 xff1f 写在一个文件 xff1f 2 框
  • SpringBoot(七)Web开发静态资源处理

    1 静态资源处理 静态资源映射规则 首先 xff0c 我们搭建一个普通的 SpringBoot 项目 xff0c 回顾一下HelloWorld程序 xff01 写请求非常简单 xff0c 那我们要引入我们前端资源 xff0c 我们项目中有许
  • SpringBoot(八)Thymeleaf模板引擎

    模板引擎 前端交给我们的页面 xff0c 是 html 页面 如果是我们以前开发 xff0c 我们需要把他们转成 jsp 页面 xff0c jsp 好处就是当我们查出一些数据转发到JSP页面以后 xff0c 我们可以用jsp轻松实现数据的显
  • SpringBoot(九)MVC自动配置原理【深入源码】

    官网阅读 在进行项目编写前 xff0c 我们还需要知道一个东西 xff0c 就是 SpringBoot 对我们的 SpringMVC 还做了哪些配置 xff0c 包括如何扩展 xff0c 如何定制 只有把这些都搞清楚了 xff0c 我们在之
  • SpringBoot(十)RestfulCRUD

    我们先创建一个SpringBoot的 web 项目 xff0c 并导入thymeleaf lombok 坐标 1 环境搭建 首先我们先将静态资源及页面拷入到项目中 然后我们编写 pojo dao类 这里我们没有连接数据库 xff0c Dao
  • PyTorch:torch.sum

    torch sum 函数定义 xff1a torch sum input dim keepdim 61 False dtype 61 None Tensor 作用 xff1a 返回输入tensor的指定维度dim上的和 参数keepdim表
  • SpringBoot(十一)国际化

    有的时候 xff0c 我们的网站会去涉及中英文甚至多语言的切换 xff0c 这时候我们就需要学习国际化了 xff01 准备工作 先在IDEA中统一设置 properties 的编码问题 xff01 编写国际化配置文件 xff0c 抽取页面需
  • SpringBoot(十二)整合JDBC

    SpringData简介 对于数据访问层 xff0c 无论是 SQL 关系型数据库 还是 NOSQL 非关系型数据库 xff0c Spring Boot 底层都是采用 Spring Data 的方式进行统一处理 Spring Boot 底层
  • SpringBoot(十三)整合Druid

    Druid简介 Java程序很大一部分要操作数据库 xff0c 为了提高性能操作数据库的时候 xff0c 又不得不使用数据库连接池 Druid 是阿里巴巴开源平台上一个数据库连接池实现 xff0c 结合了 C3P0 DBCP 等 DB 池的
  • SpringBoot(十四)整合MyBatis

    官方文档 xff1a http mybatis org spring boot starter mybatis spring boot autoconfigure Maven仓库地址 xff1a https mvnrepository co