javascript
3、SpringBoot整合MyBatis注解版及配置文件版
目錄
1、配置pom.xml
2、配置application.yml
?3、配置DruidConfig關聯(lián)yml的配置文件spring.datasource
4、創(chuàng)建數(shù)據(jù)庫及數(shù)據(jù)庫表結構
5、創(chuàng)建對應的實體類
? ??1)Department
? ??2)Employee
6、創(chuàng)建對應的Mapper?
? ??1)創(chuàng)建DepartmentMapper
7、創(chuàng)建DeptController
8、瀏覽器訪問
? ??1)新增測試:
? ? ? ??返回結果
? ??2)查詢測試:
返回結果
9、解決駝峰命名問題
? ??1)使用配置類的方式
? ???2)使用配置文件的方式? ??
10、省寫@Mapper 注解,統(tǒng)一配置在啟動入口
11、配置文件的方式整合Mybatis
? ??1)創(chuàng)建EmployeeMapper類
? ??2)創(chuàng)建mybatis/mapper/EmployeeMapper.xml
? ??3)創(chuàng)建mybatis/mybatis-config.xml
? ??4) 在application.yml文件中配置mybatis文件的位置
? ??5)創(chuàng)建EmpController類
? ??6)測試配置版springboot整合mybatis
?
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><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.6.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.mi</groupId><artifactId>spring-boot-mybatis</artifactId><version>0.0.1-SNAPSHOT</version><name>spring-boot-mybatis</name><description>spring-boot-mybatis project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.1</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!--引入自定義數(shù)據(jù)源--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.18</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>?
2、配置application.yml
spring:datasource:username: rootpassword: rooturl: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTCdriver-class-name: com.mysql.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSourceinitialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true # ? 配置監(jiān)控統(tǒng)計攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計,'wall'用于防火墻filters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500schema:- classpath:sql/department.sql- classpath:sql/employee.sql
3、配置DruidConfig關聯(lián)yml的配置文件spring.datasource
package com.mi.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;/*** Created by chengwen on 2019/7/3.*/
@Configuration
public class DruidConfig {@Bean@ConfigurationProperties(prefix = "spring.datasource")public DataSource druid(){return new DruidDataSource();}//配置Druid的監(jiān)控//1、配置一個管理后臺的servlet@Beanpublic ServletRegistrationBean statViewServlet(){ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");Map<String,String> initParms = new HashMap<>();initParms.put("loginUsername","admin");initParms.put("loginPassword","123456");initParms.put("allow",""); //默認是允許所有訪問initParms.put("deny","192.168.15.21"); //不允許訪問bean.setInitParameters(initParms);return bean;}//2、配置一個監(jiān)控的filter@Beanpublic FilterRegistrationBean webStatFilter(){FilterRegistrationBean bean = new FilterRegistrationBean();bean.setFilter(new WebStatFilter());Map<String,String> initParms = new HashMap<>();initParms.put("exclusions","*.js,*.css,/druid/*");bean.setInitParameters(initParms);bean.setUrlPatterns(Arrays.asList("/*"));return bean;}
}
4、創(chuàng)建數(shù)據(jù)庫及數(shù)據(jù)庫表結構
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;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;
?
5、創(chuàng)建對應的實體類
1)Department
package com.mi.bean;
/*** Created by chengwen on 2019/7/3.*/
public class Department {private ?Integer id;private String departmentName;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getDepartmentName() {return departmentName;}public void setDepartmentName(String departmentName) {this.departmentName = departmentName;}
}
2)Employee
package com.mi.bean;/*** Created by chengwen on 2019/7/3.*/
public class Employee {private Integer id;private String lastName;private Integer gender;private String email;private Integer dId;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}public Integer getGender() {return gender;}public void setGender(Integer gender) {this.gender = gender;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public Integer getdId() {return dId;}public void setdId(Integer dId) {this.dId = dId;}
}
?
6、創(chuàng)建對應的Mapper
1)創(chuàng)建DepartmentMapper
package com.mi.mapper;
import com.mi.bean.Department;
import org.apache.ibatis.annotations.*;/*** Created by chengwen on 2019/7/3.*/
//指定這是一個操作數(shù)據(jù)庫的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);//@Options注解用于獲取自增主鍵返回給前端@Options(useGeneratedKeys = true,keyProperty = "id")@Options(useGeneratedKeys = true,keyProperty = "id")@Insert("insert into department(departmentName) values (#{departmentName})")public int insertDept(Department department);@Update("update department set departmentName=#{departmentName} where id=#{id}")public int updateDept(Department department);}
?
7、創(chuàng)建DeptController
package com.mi.controller;import com.mi.bean.Department; import com.mi.mapper.DepartmentMapper; 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;/*** Created by chengwen on 2019/7/3.*/ @RestController public class DeptController {@AutowiredDepartmentMapper departmentMapper;@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;} }?
8、瀏覽器訪問
1)新增測試:
http://localhost:8080/dept?departmentName=CC
返回結果
{"id":3,"departmentName":"CC"}?
2)查詢測試:
http://localhost:8080/dept/1
返回結果
{"id":1,"departmentName":"AA"}
9、解決駝峰命名問題
可以使實體類的駝峰命名與數(shù)據(jù)庫的下劃線映射成功。
1)使用配置類的方式
package com.mi.config;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;/*** Created by chengwen on 2019/7/3.*/
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {@Beanpublic ConfigurationCustomizer configurationCustomizer(){return new ConfigurationCustomizer() {@Overridepublic void customize(Configuration configuration){configuration.setMapUnderscoreToCamelCase(true);}};}
}
2)使用配置文件的方式
在application.yml文件中添加配置
# 解決駝峰命名問題 mybatis:configuration:map-underscore-to-camel-case: true?
10、省寫@Mapper 注解,統(tǒng)一配置在啟動入口
使用@MapperScan(value = "com.mi.mapper")掃描所有Mapper文件
package com.mi;import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@MapperScan(value = "com.mi.mapper") @SpringBootApplication public class SpringBootMybatisApplication {public static void main(String[] args) {SpringApplication.run(SpringBootMybatisApplication.class, args);}}?
11、配置文件的方式整合Mybatis
1)創(chuàng)建EmployeeMapper類
package com.mi.mapper;
import com.mi.bean.Employee;
import org.apache.ibatis.annotations.Mapper;/*** Created by chengwen on 2019/7/3.*/
//@Mapper或者mapperScan將接口掃描到容器中
public interface EmployeeMapper {public Employee getEmpById(Integer id);public void insertEmp(Employee employee);
}
2)創(chuàng)建mybatis/mapper/EmployeeMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.mi.mapper.EmployeeMapper"><select id="getEmpById" resultType="com.mi.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>3)創(chuàng)建mybatis/mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration><settings><setting name="mapUnderscoreToCamelCase" value="true"/></settings> </configuration>
4) 在application.yml文件中配置mybatis文件的位置
spring:datasource:username: rootpassword: rooturl: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTCdriver-class-name: com.mysql.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSourceinitialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true
# ? 配置監(jiān)控統(tǒng)計攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計,'wall'用于防火墻filters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500#schema:# ?- classpath:sql/department.sql# ?- classpath:sql/employee.sql
# 解決駝峰命名問題
mybatis:#configuration:# ?map-underscore-to-camel-case: true#配置文件的方式整合mybatisconfig-location: classpath:/mybatis/mybatis-config.xmlmapper-locations: classpath:/mybatis/mapper/*.xml
5)創(chuàng)建EmpController類
package com.mi.controller; import com.mi.bean.Employee; import com.mi.mapper.EmployeeMapper; 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;/*** Created by chengwen on 2019/7/3.*/ @RestController public class EmpController {@AutowiredEmployeeMapper employeeMapper;@GetMapping("emp/{id}")public Employee getEmp(@PathVariable("id") Integer id){return employeeMapper.getEmpById(id);}}6)測試配置版springboot整合mybatis
http://localhost:8080/emp/1?
測試結果
{"id":1,"lastName":"zhangsan","gender":1,"email":"zhangsan@163.com","dId":1}
?
?
總結
以上是生活随笔為你收集整理的3、SpringBoot整合MyBatis注解版及配置文件版的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Hadoop 2.x 完全分布式HA集群
- 下一篇: 1、SpringBoot整合JPA