三、整合MyBatis
1.引入mybatis-starter(mybatis-spring-boot-starter)依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
依赖关系图
2.配置数据源的相关属性(见上篇博客整合Druid)
1.引入druid数据源找到对应版本的druid依赖导入
<!--引入druid数据源-->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
2.配置文件引用上一篇博客整合Druid的配置文件
spring:
datasource:
username: root
password: 1234567890
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
driver-class-name: com.mysql.jdbc.Driver
initialization-mode: always
#数据源的其他配置
type: com.alibaba.druid.pool.DruidDataSource
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,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,slf4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
# schema:
# - classpath:sql/department.sql
# - classpath:sql/employee.sql
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
3.编写配置类将数据源进行配置
package com.atorg.springboot.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix ="spring.datasource")//生效的配置文件是从配置文件的spring.datasource开始
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置druid监控
//1.配置管理后台的servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean=new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
Map<String,String> initParams =new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
initParams.put("allow", "");//默认允许所有
initParams.put("deny", "192.168.43.177");
bean.setInitParameters(initParams);
return bean;
}
//2.配置一个监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams=new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
3.给数据库建表
department.sql文件
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`departmentName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
employee.sql文件
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`lastName` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`gender` int(2) DEFAULT NULL,
`d_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
1.在配置文件中说明建表sql文件的位置(启动程序自动创建数据表)
schema:
- classpath:sql/department.sql
- classpath:sql/employee.sql
注意,数据表在程序运行开始就会自动创建,所以运行一次以后就将此建表语句删除,防止运行一次新建一次数据表
4.创建java bean进行数据封装
Department .class
package com.atorg.springboot.bean;
public class Department {
private Integer id;
private String departmentName;
public Integer getId() {
return id;
}
public String getDepartmentName() {
return departmentName;
}
public void setId(Integer id) {
this.id = id;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
}
Employee.class
package com.atorg.springboot.bean;
public class Employee {
private Integer id;
private String lastName;
private Integer gender;
private String email;
private Integer dId;
public Integer getId() {
return id;
}
public String getLastName() {
return lastName;
}
public Integer getGender() {
return gender;
}
public String getEmail() {
return email;
}
public Integer getdId() {
return dId;
}
public void setId(Integer id) {
this.id = id;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public void setEmail(String email) {
this.email = email;
}
public void setdId(Integer dId) {
this.dId = dId;
}
}
5.使用MyBatis对数据库进行增删改查(MyBatis注解版)
1.编写Mapper类对数据库进行增删改查
package com.atorg.springboot.mapper;
import com.atorg.springboot.bean.Department;
import org.apache.ibatis.annotations.*;
//指定这是一个操作数据库的mapper
@Mapper //如果不标明Mapper,MyBatis就无法工作
public interface DepartmentMapper {
//数据库查询字段
@Select("select * from department where id=#{id}")
public Department getDeptById(Integer id);
//数据库删除字段
@Delete("delete from department where id=#{id}")
public int deleteDeptById(Integer id);
//数据库信息插入
@Options(useGeneratedKeys = true,keyProperty = "id") //指定那个是自增主键,不写这句在插入数据时id会显示null
@Insert("insert into department(department_name) values(#{departmentName})")
public int insertDept(Department department);
//数据库字段信息更新
@Update("update department set department_name=#{departmentName} where id=#{id}")
public int updateDept(Department department);
}
如果我们的Mapper类特别多的情况下,在每一个类上都添加Mapper注解就太麻烦了,此时我们可以在主配置类上添加一下注解
MapperScan:批量扫描所有的Mapper接口
@MapperScan(value = "com.atorg.springboot.mapper") //指定添加@Mapper注解的类的位置,主动给其类上添加@Mapper注解,不用我们一个一个去添加
2.编写controller进行测试
DeptController.class
package com.atorg.springboot.controller;
import com.atorg.springboot.bean.Department;
import com.atorg.springboot.bean.Employee;
import com.atorg.springboot.mapper.DepartmentMapper;
import com.atorg.springboot.mapper.EmployeeMapper;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DeptController {
@Autowired //注入DepartmentMapper
DepartmentMapper departmentMapper;
@GetMapping("/dept/{id}") //处理映射(发送请求){id}以占位符的形式取出id,@PathVariable路径变量
public Department getDepartment(@PathVariable("id") Integer id){
return departmentMapper.getDeptById(id);
}
@GetMapping("/dept")
public Department insertDept(Department department){
departmentMapper.insertDept(department);
return department;
}
}
查询第一个人的信息:http://localhost:8080/dept/1
插入数据http://localhost:8080/dept?departmentName=FF
数据库信息增加
问题:如果将数据库表的列名改为department_name原来为departmentName此时departmentName不能被数据库封装,此时还要开启驼峰命名法(不写配置文件的写法)写一个配置类MyBatisConfig自定义MyBatis的配置规则
MyBatisConfig.class作用:开启驼峰命名法
package com.atorg.springboot.config;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
6.使用MyBatis对数据库进行增删改查(MyBatis配置文件版)
1.编写EmployeeMapper接口
package com.atorg.springboot.mapper;
import com.atorg.springboot.bean.Employee;
//@Mapper或者@MapperScan将接口扫描到容器中
public interface EmployeeMapper {
//查询员工
public Employee getEmpById(Integer id);
//插入员工
public void insertEmp(Employee employee);
}
2.配置全局配置文件
全局配置文件参考
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings> //开启驼峰命名法
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
sql映射文件参考
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.atorg.springboot.mapper.EmployeeMapper">//跟EmployeeMapper接口进行绑定
<!-- public Employee getEmpByTd(Integer id);
public void insertEmp(Employee employee);-->
//配置文件形式查询数据
<select id="getEmpById" resultType="com.atorg.springboot.bean.Employee">//resultType指明返回值类型
SELECT * FROM employee WHERE id=#{id}
</select>
//配置文件形式插入数据
<insert id="insertEmp">
INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
</insert>
</mapper>
要让MyBatis知道mybatis的全局配置文件以及sql映射文件存在并且起作用我们要在yml中指明MyBatis全局配置文件以及sql映射文件Mapper的位置
配置文件版的核心步骤
mybatis:
config-location: classpath:mybatis/mybatis-config.xml #mybatis全局配置文件的位置
mapper-locations: classpath:mybatis/mapper/*.xml #sql映射文件的位置
3.编写Controller进行测试
@Autowired//注入EmployeeMapper
EmployeeMapper employeeMapper;
@GetMapping("/emp/{id}")
public Employee getEmp(@PathVariable("id") Integer id){
return employeeMapper.getEmpById(id);
}
启动应用运行截图