SpringBoot09:整合MyBatis

郎家岭伯爵 2021年12月04日 768次浏览

整合MyBatis

官方文档
Maven仓库地址

整合测试

  1. 导入 MyBatis 所需要的依赖
  1. <dependency>
  2. <groupId>org.mybatis.spring.boot</groupId>
  3. <artifactId>mybatis-spring-boot-starter</artifactId>
  4. <version>2.1.1</version>
  5. </dependency>
  1. 配置数据库连接信息(不变)
  1. spring:
  2. datasource:
  3. username: root
  4. password: 123456
  5. #?serverTimezone=UTC解决时区的报错
  6. url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
  7. driver-class-name: com.mysql.cj.jdbc.Driver
  8. type: com.alibaba.druid.pool.DruidDataSource

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

  22. #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
  23. #如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
  24. #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
  25. filters: stat,wall,log4j
  26. maxPoolPreparedStatementPerConnectionSize: 20
  27. useGlobalDataSourceStat: true
  28. connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
  1. 测试数据库是否连接成功!

  2. 创建实体类,导入 Lombok!

    1. Department.java
  1. package com.kuang.pojo;

  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;

  5. @Data
  6. @NoArgsConstructor
  7. @AllArgsConstructor
  8. public class Department {

  9. private Integer id;
  10. private String departmentName;

  11. }
  1. 创建mapper目录以及对应的 Mapper 接口
    1. DepartmentMapper.java
  1. //@Mapper : 表示本类是一个 MyBatis 的 Mapper
  2. @Mapper
  3. @Repository
  4. public interface DepartmentMapper {

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

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

  9. }
  1. 对应的Mapper映射文件
    1. DepartmentMapper.xml
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

  5. <mapper namespace="com.kuang.mapper.DepartmentMapper">

  6. <select id="getDepartments" resultType="Department">
  7. select * from department;
  8. </select>

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

  12. </mapper>
  1. maven配置资源过滤问题
  1. <resources>
  2. <resource>
  3. <directory>src/main/java</directory>
  4. <includes>
  5. <include>**/*.xml</include>
  6. </includes>
  7. <filtering>true</filtering>
  8. </resource>
  9. </resources>
  1. 编写部门的 DepartmentController 进行测试!
  1. @RestController
  2. public class DepartmentController {

  3. @Autowired
  4. DepartmentMapper departmentMapper;

  5. // 查询全部部门
  6. @GetMapping("/getDepartments")
  7. public List<Department> getDepartments(){
  8. return departmentMapper.getDepartments();
  9. }

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

  15. }

启动项目访问进行测试!

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

  1. 新建一个pojo类 Employee;
  1. @Data
  2. @AllArgsConstructor
  3. @NoArgsConstructor
  4. public class Employee {

  5. private Integer id;
  6. private String lastName;
  7. private String email;
  8. //1 male, 0 female
  9. private Integer gender;
  10. private Integer department;
  11. private Date birth;

  12. private Department eDepartment; // 冗余设计

  13. }
  1. 新建一个 EmployeeMapper 接口
  1. //@Mapper : 表示本类是一个 MyBatis 的 Mapper
  2. @Mapper
  3. @Repository
  4. public interface EmployeeMapper {

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

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

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

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

  13. }
  1. 编写 EmployeeMapper.xml 配置文件
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

  5. <mapper namespace="com.kuang.mapper.EmployeeMapper">

  6. <resultMap id="EmployeeMap" type="Employee">
  7. <id property="id" column="eid"/>
  8. <result property="lastName" column="last_name"/>
  9. <result property="email" column="email"/>
  10. <result property="gender" column="gender"/>
  11. <result property="birth" column="birth"/>
  12. <association property="eDepartment" javaType="Department">
  13. <id property="id" column="did"/>
  14. <result property="departmentName" column="dname"/>
  15. </association>
  16. </resultMap>

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

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

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

  29. <delete id="delete" parameterType="int">
  30. delete from employee where id = #{id}
  31. </delete>

  32. </mapper>
  1. 编写EmployeeController类进行测试
  1. @RestController
  2. public class EmployeeController {

  3. @Autowired
  4. EmployeeMapper employeeMapper;

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

  10. @GetMapping("/save")
  11. public int save(){
  12. Employee employee = new Employee();
  13. employee.setLastName("kuangshen");
  14. employee.setEmail("qinjiang@qq.com");
  15. employee.setGender(1);
  16. employee.setDepartment(101);
  17. employee.setBirth(new Date());
  18. return employeeMapper.save(employee);
  19. }

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

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

  30. }

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


本文转载自狂神说的博客,感谢狂神开源的视频及资料。