以前用Spring構建一個項目,配置文件太過麻煩而且很容易出錯,而用SpringBoot,只需要填寫必要的配置文件,可以很輕鬆整合Mybatis。下面開啓SpringBoot之旅吧!
1、pom.xml引入相關依賴
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jlu</groupId>
<artifactId>springboot_mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot_mybatis</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<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>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--引入druid-->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.minidev</groupId>
<artifactId>json-smart</artifactId>
<version>2.2.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、使用yaml配置文件比XML更加簡潔明瞭。application.yml
spring:
datasource:
# 數據源基本配置
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.0.113:3306/mybatis
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,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
#建表時用
# schema:
# - classpath:sql/department.sql
# - classpath:sql/employee.sql
#-----以下是xml配置文件方式開發-------------
mybatis:
# 指定全局配置文件位置
config-location: classpath:mybatis/mybatis-config.xml
# 指定sql映射文件位置
mapper-locations: classpath:mybatis/mapper/*.xml
如果想要自動建表,可在要第一次運行前將schema打開,建表sql放到指定路徑下
3、實體類:Department(註解版測試用)和Employee(註解+XML配置版測試用)
public class Department {
private Integer id;
private String departmentName;
//getters sttters toString...
}
public class Employee {
private Integer id;
private String lastName;
private Integer gender;
private String email;
private Integer dId;
//getters setters toString...
}
4、整合Druid數據源
@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.0.113");
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;
}
}
5、實體類對應的Mapper
DepartmentMapper:
//@Mapper指定這是一個操作數據庫的mapper
//@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);
//useGeneratedKeys:開啓自增主鍵,keyProperty:Department中哪個屬性與主鍵映射
@Options(useGeneratedKeys = true,keyProperty = "id")
@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);
}
EmplyeeMapper:
//@Mapper或者@MapperScan將接口掃描裝配到容器中
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
public void insertEmp(Employee employee);
}
注意mapper接口中如果不標明@Mapper,也可在主程序類裏用@MapperScan註解掃描包
//使用MapperScan批量掃描所有的Mapper接口;
@MapperScan(value = "com.jlu.springboot.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
}
}
第①方式:全註解版
1、編寫controller:
@RestController
public class DeptController {
@Autowired
DepartmentMapper departmentMapper;
//根據id查詢部門信息
@GetMapping("/dept/{id}")
public Department getDepartment(@PathVariable("id") Integer id){
return departmentMapper.getDeptById(id);
}
//插入數據,並返回部門信息
@GetMapping("/dept")
public Department insertDept(Department department){
departmentMapper.insertDept(department);
return department;
}
}
2、mapper接口
//@Mapper指定這是一個操作數據庫的mapper
//@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);
//useGeneratedKeys:開啓自增主鍵,keyProperty:Department中哪個屬性與主鍵映射
@Options(useGeneratedKeys = true,keyProperty = "id")
@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);
}
3、啓動和測試:
訪問http://localhost:8080/dept?departmentName=研發部(其中id是自增長,mapper中用@Options註解標明),向數據庫插入一條數據
頁面返回數據:{"id":1,"departmentName":"研發部"}
訪問http://localhost:8080/dept/1,查詢id爲1的數據---{"id":1,"departmentName":"研發部"}
問題:
當實體類屬性departmentName和表字段depaartment_name不一致時,訪問http://localhost:8080/dept/1(返回的jsons數據{"id":1,"departmentName":NULL})。由於用全註解版,不能用XML配置開啓駝峯命名規則,我們有2中辦法解決這問題。
其一可以用@Results註解指定映射關係如下:
@Results({
@Result(property = "departmentName", column = "department_name")
})
@Select("select * from department where id=#{id}")
public Department getDeptById(Integer id);
其二我們可以編寫一個自定義MyBatis的配置規則配置類;給容器中添加一個ConfigurationCustomizer;開啓駝峯命名規則
(值得注意的是如果application.yml中引入了配置文件這個就沒用了?)
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return new ConfigurationCustomizer() {
@Override
public void customize(Configuration configuration) {
//全局開啓駝峯命名規則
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
第②種方式:XML
1、controller
@RestController
public class DeptController {
@Autowired
EmployeeMapper employeeMapper;
//數據插入略...
//根據id查詢僱員信息
@GetMapping("/emp/{id}")
public Employee getEmp(@PathVariable("id") Integer id){
return employeeMapper.getEmpById(id);
}
}
2、mapper接口:
//@Mapper或者@MapperScan將接口掃描裝配到容器中
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
public void insertEmp(Employee employee);
}
3、SQL映射文件和mapper全局配置文件
類路徑下/mybaties/mapper/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.jlu.springboot.mapper.EmployeeMapper">
<select id="getEmpById" resultType="com.jlu.springboot.bean.Employee">
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>
類路徑下/mybaties/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>
<!--mybatis開啓駝峯映射規則,數據庫字段自動映射爲實體類屬性-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
4、在application.yml在全局配置文件中
5、啓動和測試
訪問http://localhost:8080/emp/1,查詢id爲1的數據
{"id":1,"lastName":"zhangSan",gender:0,email:"[email protected]",dId:1}