SpringBoot 2.1.7 集成 Mybatis
使用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,新建项目并填写基本信息
-
3.选择需要的工具
选择Web
、MySQL Driver
和MyBatis Framework
等必要依赖:
- 4.确认完成,build.gradle如下:
plugins {
id 'org.springframework.boot' version '2.1.7.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
group = 'com.wxx'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
configurations {
developmentOnly
runtimeClasspath {
extendsFrom developmentOnly
}
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.0'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'mysql:mysql-connector-java'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
4.集成Mybatis
4.1 创建Domain
实体类有:Student、Score,与数据库表相对应;
Student
:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Student {
private Integer id;
private String name;
private Integer age;
private String sex;
private String hobbies;
private String address;
}
Score
:
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Score {
private Integer id;
private Integer studentId;
private String studentName;
private String subject;
private Integer subjectScore;
}
StudentScore、StudentScores,是关联查询时使用的,并没有相对应的表;
StudentScore
:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class StudentScore {
private String name;
private Integer age;
private String sex;
private Score score;
}
StudentScores
:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class StudentScores {
private String name;
private Integer age;
private String sex;
private List<Score> scoreList;
}
注:@Data,@Builder,@AllArgsConstructor,@NoArgsConstructor为lombok的注解
4.2 配置文件
application.properties
:
spring.application.name=student-service
spring.boot.admin.client.enabled=true
spring.profiles.active=dev
配置日志、MySQL连接、MyBatis扫描包路径等信息;
application-dev.yml
:
server:
connection-timeout: 30000ms
port: 8081
servlet.context-path: /
logging:
path: ./
file: st.log
#max-size: 10M
#max-history: 1
level:
root: INFO
org:
springframework:
web: INFO
com:
wxx:
sbmm:
mapper: DEBUG
spring:
data:
mongodb:
database: studentService
host: localhost
port: 27017
datasource:
# 遇到时区问题用这个
# jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
url: jdbc:mysql://localhost:3306/studentService?useSSL=false&useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 12345678
# schema.sql中一般存放的是DDL脚本,即通常为创建或更新库表的脚本
# data.sql中一般是DML脚本,即通常为数据插入脚本
schema: classpath:schema.sql
data: classpath:data.sql
platform: mysql
initialization-mode: always
continue-on-error: false
#data-password:
#data-username:
#schema-password:
#schema-username:
sql-script-encoding: utf-8
separator: ;
# type: com.alibaba.druid.pool.DruidDataSource
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.wxx.sbmm.domain
# config-location:
configuration:
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配置
信息,参考: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图:
schema.sql
:初始化库表SQL
CREATE DATABASE IF NOT EXISTS `studentService`;
CREATE TABLE IF NOT EXISTS `t_student` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` VARCHAR(255) DEFAULT "" COMMENT '姓名',
`age` INT DEFAULT 10 COMMENT '年龄',
`sex` VARCHAR(255)DEFAULT "Male" COMMENT '性别',
`hobbies` VARCHAR(255) DEFAULT "" COMMENT '爱好',
`address` VARCHAR(255) DEFAULT "" COMMENT '住址',
PRIMARY KEY(`id`),
UNIQUE INDEX `idx_student_name_address` (`name`,`address`) USING BTREE
)ENGINE = INNODB DEFAULT CHARSET=utf8 AUTO_INCREMENT = 1 COMMENT '学生表';
CREATE TABLE IF NOT EXISTS `t_score` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT 'ID',
`student_id` INT DEFAULT 0 COMMENT '学生ID',
`student_name` VARCHAR(255) DEFAULT "" COMMENT '学生姓名',
`subject` VARCHAR(255) DEFAULT "" COMMENT '学科',
`subject_score` INT COMMENT '学科成绩',
PRIMARY KEY(`id`),
UNIQUE INDEX `idx_score_studentname_subject` (`student_name`,`subject`) USING BTREE ,
FOREIGN KEY (student_id) REFERENCES t_student (id)
)ENGINE = INNODB DEFAULT CHARSET=utf8 AUTO_INCREMENT = 1 COMMENT '学生成绩表';
data.sql
:初始化数据SQL
INSERT INTO t_student (name,age, sex, hobbies, address)
SELECT "Even",9,"Male","ShuXue,English","XiAn" FROM DUAL WHERE NOT EXISTS(SELECT 1 FROM t_student WHERE name = "Even");
INSERT INTO t_st