1.环境信息

使用SpringBoot集成Mybatis有两种方式,本文使用IDEA搭建:

  • 1.Spring Initializr
  • 2.使用IDEA插件

环境信息OS:Win10 Jdk:JavaSE 8 Ide:Idea Ultimate MySQL:8.0.16 MyBatis:3.5.2 Spring Boot:2.1.7.RELEASE

2.创建Web项目

Idea集成了Spring Initializr,新建项目:

  • 1.选择Spring Initializr,新建项目并填写基本信息
    SpringBoot 2.x 集成 Mybatis - 图1
  • 3.选择需要的工具
    选择WebMySQL DriverMyBatis Framework等必要依赖:

SpringBoot 2.x 集成 Mybatis - 图2

  • 4.确认完成,build.gradle如下:
  1. plugins {
  2. id 'org.springframework.boot' version '2.1.7.RELEASE'
  3. id 'java'
  4. }
  5. apply plugin: 'io.spring.dependency-management'
  6. group = 'com.wxx'
  7. version = '0.0.1-SNAPSHOT'
  8. sourceCompatibility = '1.8'
  9. configurations {
  10. developmentOnly
  11. runtimeClasspath {
  12. extendsFrom developmentOnly
  13. }
  14. compileOnly {
  15. extendsFrom annotationProcessor
  16. }
  17. }
  18. repositories {
  19. mavenCentral()
  20. }
  21. dependencies {
  22. implementation 'org.springframework.boot:spring-boot-starter-web'
  23. implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.0'
  24. compileOnly 'org.projectlombok:lombok'
  25. developmentOnly 'org.springframework.boot:spring-boot-devtools'
  26. runtimeOnly 'mysql:mysql-connector-java'
  27. annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
  28. annotationProcessor 'org.projectlombok:lombok'
  29. testImplementation 'org.springframework.boot:spring-boot-starter-test'
  30. }

4.集成Mybatis

4.1 创建Domain

实体类有:Student、Score,与数据库表相对应;
Student:

  1. @Data
  2. @AllArgsConstructor
  3. @NoArgsConstructor
  4. @Builder
  5. public class Student {
  6. private Integer id;
  7. private String name;
  8. private Integer age;
  9. private String sex;
  10. private String hobbies;
  11. private String address;
  12. }

Score:

  1. @Data
  2. @Builder
  3. @AllArgsConstructor
  4. @NoArgsConstructor
  5. public class Score {
  6. private Integer id;
  7. private Integer studentId;
  8. private String studentName;
  9. private String subject;
  10. private Integer subjectScore;
  11. }

StudentScore、StudentScores,是关联查询时使用的,并没有相对应的表;

StudentScore:

  1. @Data
  2. @AllArgsConstructor
  3. @NoArgsConstructor
  4. @Builder
  5. public class StudentScore {
  6. private String name;
  7. private Integer age;
  8. private String sex;
  9. private Score score;
  10. }

StudentScores:

  1. @Data
  2. @AllArgsConstructor
  3. @NoArgsConstructor
  4. @Builder
  5. public class StudentScores {
  6. private String name;
  7. private Integer age;
  8. private String sex;
  9. private List<Score> scoreList;
  10. }

:@Data,@Builder,@AllArgsConstructor,@NoArgsConstructor为lombok的注解

4.2 配置文件

application.properties

  1. spring.application.name=student-service
  2. spring.boot.admin.client.enabled=true
  3. spring.profiles.active=dev

配置日志、MySQL连接、MyBatis扫描包路径等信息;
application-dev.yml

  1. server:
  2. connection-timeout: 30000ms
  3. port: 8081
  4. servlet.context-path: /
  5. logging:
  6. path: ./
  7. file: st.log
  8. #max-size: 10M
  9. #max-history: 1
  10. level:
  11. root: INFO
  12. org:
  13. springframework:
  14. web: INFO
  15. com:
  16. wxx:
  17. sbmm:
  18. mapper: DEBUG
  19. spring:
  20. data:
  21. mongodb:
  22. database: studentService
  23. host: localhost
  24. port: 27017
  25. datasource:
  26. # 遇到时区问题用这个
  27. # jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
  28. url: jdbc:mysql://localhost:3306/studentService?useSSL=false&useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
  29. driver-class-name: com.mysql.cj.jdbc.Driver
  30. username: root
  31. password: 12345678
  32. # schema.sql中一般存放的是DDL脚本,即通常为创建或更新库表的脚本
  33. # data.sql中一般是DML脚本,即通常为数据插入脚本
  34. schema: classpath:schema.sql
  35. data: classpath:data.sql
  36. platform: mysql
  37. initialization-mode: always
  38. continue-on-error: false
  39. #data-password:
  40. #data-username:
  41. #schema-password:
  42. #schema-username:
  43. sql-script-encoding: utf-8
  44. separator: ;
  45. # type: com.alibaba.druid.pool.DruidDataSource
  46. mybatis:
  47. mapper-locations: classpath:mapper/*.xml
  48. type-aliases-package: com.wxx.sbmm.domain
  49. # config-location:
  50. configuration:
  51. cache-enabled: true

MyBatis配置信息,参考[Configuration部分]:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/index.html

这里使用springboot默认的数据库连接池;
配置中使用schema.sql存放创建库表的脚本,data.sql数据插入脚本,这是springboot的默认配置;
SpringBoot 2.x 集成 Mybatis - 图3

更多SpringBoot配置信息,参考:https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

4.3 配置数据库初始化脚本

数据库为:studentService
手动创建数据库:CREATE SCHEMA studentService DEFAULT CHARACTER SET utf8 ;
包含两个表,针对它们进行单表查询和关联查询:
学生表:t_student
成绩表:t_score
ER图:
SpringBoot 2.x 集成 Mybatis - 图4

schema.sql:初始化库表SQL

  1. CREATE DATABASE IF NOT EXISTS `studentService`;
  2. CREATE TABLE IF NOT EXISTS `t_student` (
  3. `id` INT NOT NULL AUTO_INCREMENT COMMENT 'ID',
  4. `name` VARCHAR(255) DEFAULT "" COMMENT '姓名',
  5. `age` INT DEFAULT 10 COMMENT '年龄',
  6. `sex` VARCHAR(255)DEFAULT "Male" COMMENT '性别',
  7. `hobbies` VARCHAR(255) DEFAULT "" COMMENT '爱好',
  8. `address` VARCHAR(255) DEFAULT "" COMMENT '住址',
  9. PRIMARY KEY(`id`),
  10. UNIQUE INDEX `idx_student_name_address` (`name`,`address`) USING BTREE
  11. )ENGINE = INNODB DEFAULT CHARSET=utf8 AUTO_INCREMENT = 1 COMMENT '学生表';
  12. CREATE TABLE IF NOT EXISTS `t_score` (
  13. `id` INT NOT NULL AUTO_INCREMENT COMMENT 'ID',
  14. `student_id` INT DEFAULT 0 COMMENT '学生ID',
  15. `student_name` VARCHAR(255) DEFAULT "" COMMENT '学生姓名',
  16. `subject` VARCHAR(255) DEFAULT "" COMMENT '学科',
  17. `subject_score` INT COMMENT '学科成绩',
  18. PRIMARY KEY(`id`),
  19. UNIQUE INDEX `idx_score_studentname_subject` (`student_name`,`subject`) USING BTREE ,
  20. FOREIGN KEY (student_id) REFERENCES t_student (id)
  21. )ENGINE = INNODB DEFAULT CHARSET=utf8 AUTO_INCREMENT = 1 COMMENT '学生成绩表';

data.sql:初始化数据SQL

  1. INSERT INTO t_student (name,age, sex, hobbies, address)
  2. SELECT "Even",9,"Male","ShuXue,English","XiAn" FROM DUAL WHERE NOT EXISTS(SELECT 1 FROM t_student WHERE name = "Even");
  3. INSERT INTO t_student (name,age, sex, hobbies, address)
  4. SELECT "Weison",11,"Male","XuWen,WuLi","HeNan" FROM DUAL WHERE NOT EXISTS(SELECT 1 FROM t_student WHERE name = "Weison");
  5. INSERT INTO t_student (name,age, sex, hobbies, address)
  6. SELECT "Angule",13,"Female","XuWen,English","Chengdu" FROM DUAL WHERE NOT EXISTS(SELECT 1 FROM t_student WHERE name = "Angule");
  7. INSERT INTO t_score (student_id,student_name, subject, subject_score)
  8. SELECT 1,"Even","YuWen",90 FROM DUAL WHERE NOT EXISTS(SELECT 1 FROM t_score WHERE student_name = "Even" and subject ="YuWen");
  9. INSERT INTO t_score (student_id,student_name, subject, subject_score)
  10. SELECT 1,"Even","ShuXue",89 FROM DUAL WHERE NOT EXISTS(SELECT 1 FROM t_score WHERE student_name = "Even" and subject ="ShuXue");
  11. INSERT INTO t_score (student_id,student_name, subject, subject_score)
  12. SELECT 1,"Even","English",67 FROM DUAL WHERE NOT EXISTS(SELECT 1 FROM t_score WHERE student_name = "Even" and subject ="English");
  13. INSERT INTO t_score (student_id,student_name, subject, subject_score)
  14. SELECT 2,"Weison","YuWen",69 FROM DUAL WHERE NOT EXISTS(SELECT 1 FROM t_score WHERE student_name = "Weison" and subject ="YuWen");
  15. INSERT INTO t_score (student_id,student_name, subject, subject_score)
  16. SELECT 2,"Weison","ShuXue",94 FROM DUAL WHERE NOT EXISTS(SELECT 1 FROM t_score WHERE student_name = "Weison" and subject ="ShuXue");
  17. INSERT INTO t_score (student_id,student_name, subject, subject_score)
  18. SELECT 2,"Weison","English",82 FROM DUAL WHERE NOT EXISTS(SELECT 1 FROM t_score WHERE student_name = "Weison" and subject ="English");
  19. INSERT INTO t_score (student_id,student_name, subject, subject_score)
  20. SELECT 3,"Angule","YuWen",58 FROM DUAL WHERE NOT EXISTS(SELECT 1 FROM t_score WHERE student_name = "Angule" and subject ="YuWen");
  21. INSERT INTO t_score (student_id,student_name, subject, subject_score)
  22. SELECT 3,"Angule","ShuXue",73 FROM DUAL WHERE NOT EXISTS(SELECT 1 FROM t_score WHERE student_name = "Angule" and subject ="ShuXue");
  23. INSERT INTO t_score (student_id,student_name, subject, subject_score)
  24. SELECT 3,"Angule","English",91 FROM DUAL WHERE NOT EXISTS(SELECT 1 FROM t_score WHERE student_name = "Angule" and subject ="English");
  25. commit;

4.4 配置SQL XML

写sql的地方:StudentMapper.xml;

XML中sql标签idMapper接口中的方法名一致,MyBatis会对他们进行关联去实现Mapper接口;

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  4. <mapper namespace="com.wxx.sbmm.mapper.StudentMapper">
  5. <!--
  6. 执行增加操作的SQL语句
  7. 1.id和parameterType 分别与StudentMapper接口中的addStudent方法的名字和 参数类型一致
  8. 2.以#{studentName}的形式引用Student参数 的studentName属性,MyBatis将使用反射读取Student参数的此属性
  9. 3.#{studentName}中studentName大小写敏感。引用其他的属性与此一致
  10. 4.seGeneratedKeys设置为"true"表明要MyBatis获取由数据库自动生成的主键
  11. 5.keyProperty="id"指定把获取到的主键值注入到Student的id属性
  12. -->
  13. <!-- 当表中字段名跟实体类字段名不一致 或 为了返回list类型 可以定义returnMap -->
  14. <resultMap id="studentMap" type="Student">
  15. <id column="id" property="id"/>
  16. <result column="name" property="name"/>
  17. <result column="age" property="age"/>
  18. <result column="sex" property="sex"/>
  19. <result column="hobbies" property="hobbies"/>
  20. <result column="address" property="address"/>
  21. </resultMap>
  22. <resultMap id="scoreResultMap" type="Score">
  23. <id column="id" property="id"/>
  24. <result column="student_id" property="studentId"/>
  25. <result column="student_name" property="studentName"/>
  26. <result column="subject" property="subject"/>
  27. <result column="subject_score" property="subjectScore"/>
  28. </resultMap>
  29. <!--增删改查 开始-->
  30. <!--新增 1-->
  31. <insert id="saveStudent" parameterType="Student" useGeneratedKeys="true" keyProperty="id">
  32. insert into t_student(name,age,sex,hobbies,address)
  33. values(#{name},#{age},#{sex},#{hobbies},#{address})
  34. </insert>
  35. <!--删除 1-->
  36. <delete id="deleteStudentByName" parameterType="String">
  37. delete from t_student where name=#{name}
  38. </delete>
  39. <!--删除 2-->
  40. <delete id="deleteByStudent" parameterType="Student">
  41. delete from t_student
  42. <where>
  43. 1=1
  44. <if test="name != null and name != ''">
  45. and name = #{name}
  46. </if>
  47. <if test="age != null and age != ''">
  48. and age = #{age}
  49. </if>
  50. <if test="sex != null and sex != ''">
  51. and sex=#{sex}
  52. </if>
  53. <if test="hobbies != null and hobbies != ''">
  54. and hobbies=#{hobbies}
  55. </if>
  56. <if test="address != null and address != ''">
  57. and address=#{address}
  58. </if>
  59. </where>
  60. </delete>
  61. <!--修改 1-->
  62. <update id="updateStudent" parameterType="Student">
  63. update t_student set
  64. <if test="age != null and age != ''">
  65. age = #{age},
  66. </if>
  67. <if test="sex != null and sex != ''">
  68. sex = #{sex},
  69. </if>
  70. <if test="hobbies != null and hobbies != ''">
  71. hobbies = #{hobbies},
  72. </if>
  73. <if test="address != null and address != ''">
  74. address = #{address}
  75. </if>
  76. where name=#{name}
  77. </update>
  78. <!--查询 1 -->
  79. <select id="findStudentByName" parameterType="String" resultMap="studentMap">
  80. SELECT * FROM t_student where name = #{name};
  81. </select>
  82. <!--查询 2 返回list的select语句,注意resultMap的值是指向前面定义好的 -->
  83. <select id="findStudents" resultMap="studentMap">
  84. select * from t_student
  85. </select>
  86. <!--查询 2 返回list的select语句,注意resultMap的值是指向前面定义好的 -->
  87. <select id="findScores" resultMap="scoreResultMap">
  88. select * from t_score
  89. </select>
  90. <!--查询 3 利用 hashMap 传递多个参数 -->
  91. <select id="findStudentByMap" parameterType="Map" resultType="Student">
  92. select * from t_student
  93. <where>
  94. 1=1
  95. <if test="name != null and name != ''">
  96. and name = #{name}
  97. </if>
  98. <if test="age != null and age != ''">
  99. and age = #{age}
  100. </if>
  101. <if test="sex != null and sex != ''">
  102. and sex=#{sex}
  103. </if>
  104. <if test="hobbies != null and hobbies != ''">
  105. and hobbies=#{hobbies}
  106. </if>
  107. <if test="address != null and address != ''">
  108. and address=#{address}
  109. </if>
  110. </where>
  111. </select>
  112. <!--查询 4 利用 hashMap 传递多个参数 -->
  113. <select id="findStudentByStudent" parameterType="Student" resultType="Student">
  114. select * from t_student
  115. <where>
  116. 1=1
  117. <if test="name != null and name != ''">
  118. and name = #{name}
  119. </if>
  120. <if test="age != null and age != ''">
  121. and age = #{age}
  122. </if>
  123. <if test="sex != null and sex != ''">
  124. and sex=#{sex}
  125. </if>
  126. <if test="hobbies != null and hobbies != ''">
  127. and hobbies=#{hobbies}
  128. </if>
  129. <if test="address != null and address != ''">
  130. and address=#{address}
  131. </if>
  132. </where>
  133. </select>
  134. <!--查询 5 Mybatis 自带的多个参数传递方法 这个时候没有 parameterType, 但用到了类似 #{param1} 类似的参数 -->
  135. <select id="findStudentByAgeAndSex" resultType="com.wxx.sbmm.domain.Student">
  136. select * from t_student where age = #{param1} and sex=#{param2}
  137. </select>
  138. <!--增删改查 结束-->
  139. <!--联合查询 开始-->
  140. <!--联合查询:studentScoreListResultMap-->
  141. <resultMap id="studentScoreListResultMap" type="com.wxx.sbmm.domain.StudentScores">
  142. <id column="aid" jdbcType="INTEGER" property="id"/>
  143. <result column="name" jdbcType="VARCHAR" javaType="String" property="name"/>
  144. <result column="age" javaType="Integer" property="age"/>
  145. <result column="sex" javaType="String" property="sex"/>
  146. <collection property="scoreList" javaType="List" ofType="Score">
  147. <id column="bid" jdbcType="INTEGER" property="id"/>
  148. <result property="studentId" column="student_id"/>
  149. <result property="studentName" column="student_name"/>
  150. <result property="subject" column="subject"/>
  151. <result property="subjectScore" column="subject_score"/>
  152. </collection>
  153. </resultMap>
  154. <!--联合查询:studentScoreResultMap-->
  155. <resultMap id="studentScoreResultMap" type="com.wxx.sbmm.domain.StudentScore">
  156. <id column="aid" jdbcType="BIGINT" javaType="Integer" property="id"/>
  157. <result property="name" jdbcType="VARCHAR" javaType="String" column="name"/>
  158. <result property="age" column="age" jdbcType="VARCHAR" javaType="Integer"/>
  159. <result property="sex" column="sex" jdbcType="VARCHAR" javaType="String"/>
  160. <association property="score" javaType="com.wxx.sbmm.domain.Score">
  161. <id property="id" column="bid"/>
  162. <result property="studentId" column="student_id"/>
  163. <result property="studentName" column="student_name"/>
  164. <result property="subject" column="subject"/>
  165. <result property="subjectScore" column="subject_score"/>
  166. </association>
  167. </resultMap>
  168. <!-- 联合查询 1 findStudentScoreList-->
  169. <select id="findStudentScores" parameterType="Integer" resultMap="studentScoreListResultMap">
  170. select
  171. a.id aid,
  172. a.name name,
  173. a.age age,
  174. a.sex sex,
  175. b.id bid,
  176. b.student_id student_id,
  177. b.student_name student_name,
  178. b.subject subject,
  179. b.subject_score subject_score
  180. from t_student a
  181. left join t_score b
  182. on a.id=b.student_id
  183. </select>
  184. <!-- 联合查询 2 findStudentScore-->
  185. <select id="findStudentScore" resultMap="studentScoreResultMap">
  186. select
  187. a.id aid,
  188. a.name name,
  189. a.age age,
  190. a.sex sex,
  191. b.id bid,
  192. b.student_id student_id,
  193. b.student_name student_name,
  194. b.subject subject,
  195. b.subject_score subject_score
  196. from t_student a
  197. left join t_score b
  198. on a.id=b.student_id
  199. where b.subject = 'English'
  200. and a.name = b.student_name
  201. </select>
  202. <!-- 联合查询 结束 -->
  203. </mapper>

Mapper XML 官方说明:http://www.mybatis.org/mybatis-3/sqlmap-xml.html#

5.代码

5.1 创建StudentMapper

使用@Mapper 注解标明 Mapper接口,MyBatis会帮我们去实现这个接口,该接口中方法与4.4xmlsql标签ID相对应:

  1. package com.wxx.sbmm.mapper;
  2. import com.wxx.sbmm.domain.Score;
  3. import com.wxx.sbmm.domain.Student;
  4. import com.wxx.sbmm.domain.StudentScore;
  5. import com.wxx.sbmm.domain.StudentScores;
  6. import org.apache.ibatis.annotations.Mapper;
  7. import org.apache.ibatis.annotations.Param;
  8. import java.util.List;
  9. import java.util.Map;
  10. @Mapper
  11. public interface StudentMapper {
  12. // 增删改查
  13. Integer saveStudent(Student student);
  14. Integer deleteStudentByName(@Param("name") String name);
  15. Integer deleteByStudent(Student student);
  16. Integer updateStudent(Student student);
  17. // 5种查询
  18. Student findStudentByName(@Param("name") String name);
  19. List<Student> findStudents();
  20. List<Student> findStudentByMap(Map<String, String> map);
  21. List<Student> findStudentByStudent(Student student);
  22. List<Student> findStudentByAgeAndSex(Integer age, String sex);
  23. // 关联查询
  24. List<StudentScores> findStudentScores();
  25. List<StudentScore> findStudentScore();
  26. }

Mapper更多信息,参考:http://www.mybatis.org/spring/mappers.html#

5.2 创建Service

  1. package com.wxx.sbmm.service;
  2. import com.wxx.sbmm.domain.Student;
  3. import com.wxx.sbmm.domain.StudentScore;
  4. import com.wxx.sbmm.domain.StudentScores;
  5. import com.wxx.sbmm.mapper.StudentMapper;
  6. import org.springframework.stereotype.Service;
  7. import javax.annotation.Resource;
  8. import java.util.List;
  9. import java.util.Map;
  10. @Service
  11. public class StudentService {
  12. @Resource
  13. private StudentMapper studentMapper;
  14. public Integer addStudent(Student student) {
  15. return studentMapper.saveStudent(student);
  16. }
  17. public Integer deleteStudentByName(String name) {
  18. return studentMapper.deleteStudentByName(name);
  19. }
  20. public Integer deleteByStudent(Student student) {
  21. return studentMapper.deleteByStudent(student);
  22. }
  23. public Integer updateStudent(Student student) {
  24. return studentMapper.updateStudent(student);
  25. }
  26. public Student findStudentByName(String name) {
  27. return studentMapper.findStudentByName(name);
  28. }
  29. public List<Student> findStudents() {
  30. return studentMapper.findStudents();
  31. }
  32. public List<Student> findStudentByMap(Map<String, String> map) {
  33. return studentMapper.findStudentByMap(map);
  34. }
  35. public List<Student> findStudentByStudent(Student student) {
  36. return studentMapper.findStudentByStudent(student);
  37. }
  38. public List<Student> findStudentByAgeAndSex(Integer age, String sex) {
  39. return studentMapper.findStudentByAgeAndSex(age, sex);
  40. }
  41. public List<StudentScores> findStudentScores() {
  42. return studentMapper.findStudentScores();
  43. }
  44. public List<StudentScore> findStudentScore() {
  45. return studentMapper.findStudentScore();
  46. }
  47. }

5.3 创建Controller

  1. package com.wxx.sbmm.controller;
  2. import com.wxx.sbmm.domain.Student;
  3. import com.wxx.sbmm.domain.StudentScore;
  4. import com.wxx.sbmm.domain.StudentScores;
  5. import com.wxx.sbmm.service.StudentService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.*;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11. @RestController
  12. public class StudentController {
  13. @Autowired
  14. private StudentService studentService;
  15. @PostMapping("/students")
  16. public Integer saveStudent(@RequestBody Student student) {
  17. Integer addNum = studentService.addStudent(student);
  18. return addNum;
  19. }
  20. @DeleteMapping("/students/{name}")
  21. public Integer deleteStudentByName(@PathVariable String name) {
  22. Integer deleteNum = studentService.deleteStudentByName(name);
  23. return deleteNum;
  24. }
  25. @DeleteMapping("/students")
  26. public Integer deleteStudentByStudent(@RequestBody Student student) {
  27. Integer deleteNum = studentService.deleteByStudent(student);
  28. return deleteNum;
  29. }
  30. @PutMapping("/students")
  31. public Integer updateStudent(@RequestBody Student student) {
  32. Integer updateNum = studentService.updateStudent(student);
  33. return updateNum;
  34. }
  35. @GetMapping("/students/{name}")
  36. public Student findStudentByName(@PathVariable String name) {
  37. Student student = studentService.findStudentByName(name);
  38. return student;
  39. }
  40. @GetMapping("/students")
  41. public List<Student> getStudentListByAgeAndSexAndHobbies() {
  42. List<Student> studentList = studentService.findStudents();
  43. return studentList;
  44. }
  45. @GetMapping("/students/map")
  46. public List<Student> findStudentByMap() {
  47. Map<String, String> map = new HashMap<>();
  48. map.put("name", "Even");
  49. List<Student> studentList = studentService.findStudentByMap(map);
  50. return studentList;
  51. }
  52. @GetMapping("/students/st")
  53. public List<Student> findStudentByStudent() {
  54. List<Student> studentList = studentService.findStudentByStudent(Student.builder().name("Even").build());
  55. return studentList;
  56. }
  57. @GetMapping("/students/{age}/{sex}")
  58. public List<Student> findStudentByAgeAndSex(@PathVariable Integer age, @PathVariable String sex) {
  59. List<Student> studentList = studentService.findStudentByAgeAndSex(age, sex);
  60. return studentList;
  61. }
  62. @GetMapping("/students/scores")
  63. public List<StudentScores> findStudentScores() {
  64. List<StudentScores> studentList = studentService.findStudentScores();
  65. return studentList;
  66. }
  67. @GetMapping("/students/score")
  68. public List<StudentScore> findStudentScore() {
  69. List<StudentScore> studentScores = studentService.findStudentScore();
  70. return studentScores;
  71. }
  72. }

5.4 最终项目

应该是这个样子:
SpringBoot 2.x 集成 Mybatis - 图5启动项目后,刷新数据库,看到数据库、表和数据都有了:
SpringBoot 2.x 集成 Mybatis - 图6

6. 测试

两个比较复杂的接口返回:
/students/scores
SpringBoot 2.x 集成 Mybatis - 图7

/students/score
SpringBoot 2.x 集成 Mybatis - 图8

代码 —> https://github.com/WeisonWei/springboot-aggregation/tree/master/springboot-mvc-mybatis