前提说明:这里顺便整合了druid,由于druid的日志问题,需要导入log4j依赖使springboot和druid各自使用自己的日志框架或者用中间包替换,统一使用springboot的日志框架。我在配置druid的filter的时候就不要使用log4j了,避开这个坑,springboot的版本变换,日志技术包也跟着变,我感觉挺难的,以后再研究研究。还是先整合吧。
一.注解方式
注解的方式不需要配置文件,根据需要可以使用配置类。
1.创建项目并引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<!--引入druid-->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
<!--jdbc驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
2.application.yml配置文件
注意到这里最后有配置mybatis的两个属性。不是说注解版的不需要配置吗?这里配置schema属性,是为了帮我们自动执行建表的sql语句,我们才不用自己去建,表生成之后,记得把它注释掉,不然每次启动应用它都执行。
注意:scheme属性的冒号后面没空格的,这个是个例外,跟yml的配置有区别。
还有一个要注意的:新版的2.0springboot配置自动执行scheme属性时会无法执行,需要再加上一句配置initialization-mode: always
spring:
datasource:
# 数据源基本配置
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/spring_mybatis?serverTimezone=UTC
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
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:
initialization-mode: always
schema:
- classpath:sql/*.sql
3.编写配置类整合druid的属性
package cn.hzu.springboot_mybatis.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")
@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.15.21");
bean.setInitParameters(initParams);
return bean;
}
//2、配置一个web监控的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;
}
}
4.编写mybatis的配置类
这个写不写都可以,根据需要使用,这里主要是用来开启驼峰命名。mybatis的配置文件的东西都可以写在这个类中。
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer() {
@Override
public void customize(Configuration configuration) {
//开启驼峰命名法
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
5.编写实体类
package cn.hzu.springboot_mybatis.bean;
public class Department {
private Integer id;
private String departmentName;
public void setId(Integer id) {
this.id = id;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public Integer getId() {
return id;
}
public String getDepartmentName() {
return departmentName;
}
}
6.编写mapper接口
注意要加@Mapper注解指定这是一个操作数据库的mapper,这个注解可以不加在这里,可以在主配置类中用MapperScan(“包名”)指定扫描这个包的所有mapper。然后将sql语句以注解的形式写在方法上
package cn.hzu.springboot_mybatis.mapper;
import cn.hzu.springboot_mybatis.bean.Department;
import org.apache.ibatis.annotations.*;
@Mapper
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")
@Insert("insert into department(departmentName) values(#{departmentName})")
public int insertDept(Department department);
@Update("update department set department_name=#{departmentName} where id=#{id}")
public int updateDept(Department department);
}
这样就整合结束了,就不编写方法测试了。也就是说这个mapper接口的方法可以直接调用了
二.xml方式
同样也需要整合druid和配置druid的监控和属性。其次还需要配置和编写mapper接口的映射文件和mybatis的全局配置文件。
1.创建项目并导包
这一步和上面注解的方式一样,我这里是写在同一个项目里面的
2.配置application.yml
这里跟上面的相比,多了指定配置文件的位置
spring:
datasource:
# 数据源基本配置
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/spring_mybatis?serverTimezone=UTC
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
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:
# # 指定全局配置文件位置
config-location: classpath:mybatis/mybatis-config.xml
# # 指定sql映射文件位置
mapper-locations: classpath:mybatis/mapper/*.xml
initialization-mode: always
schema:
- classpath:sql/*.sql
3.编写配置类整合druid的属性
这个和上面的一样
4.编写实体类
package cn.hzu.springboot_mybatis.bean;
public class Employee {
private Integer id;
private String lastName;
private Integer gender;
private String email;
private Integer 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;
}
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;
}
}
5.编写mapper接口
package cn.hzu.springboot_mybatis.mapper;
import cn.hzu.springboot_mybatis.bean.Employee;
import org.apache.ibatis.annotations.Mapper;
//@Mapper或者@MapperScan将接口扫描装配到容器中
@Mapper
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
public void insertEmp(Employee employee);
}
6.编写对应的mapper配置文件
<?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="cn.hzu.springboot_mybatis.mapper.EmployeeMapper">
<!-- public Employee getEmpById(Integer id);
public void insertEmp(Employee employee);-->
<select id="getEmpById" resultType="cn.hzu.springboot_mybatis.bean.Employee">
SELECT * FROM employee WHERE id=#{id}
</select>
<insert id="insertEmp" useGeneratedKeys="true" keyProperty="id">
INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
</insert>
</mapper>
7.mybatis全局配置文件
这个文件如果你不需要配置其他的话,这个文件可以不要,这里我来配置下驼峰
<?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>
<!--mapper配置文件不用再这里关联,再springboot的全局配置文件里直接指定位置-->
<!--mybatis的全局配置文件-->
<!--开启驼峰命名法-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
这样就整合结束了,我就不测试了。最后看看项目结构
三.项目结构
这里的controller类没有讲到,这个是我用来页面测试的,要不要无所谓。自己测试就好了。