springboot+mybatis
選中mysqldirver,資料庫驅動器
選中jdbc ,幫我們配置資料來源,連線資料庫
選中mybatis,持久層
<!-- 這個不是springboot官方出來的,是mybatis為了裝置springboot出品的--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency>
依賴圖:
引入了mybtatis-spring-boot-starter依賴之後,我們可以不引入
我們不是用springboot tomcat內建的資料來源,所以加入依賴:
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.22</version> </dependency>
前期準備:
1建立資料庫mybatis
2建立兩個資料表:
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 DEFAULT CHARSET=utf8; CREATE TABLE `department` ( `id`int(11) NOT NULL AUTO_INCREMENT, `departmentName` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
配置相關資料來源資訊:
spring:
datasource:
# 資料來源基本配置
username: root
password: 1997
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.1.101: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
編寫實體類:
Department
package com.quan.springbootmybatis.bean;
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;
}
}
Employee
package com.quan.springbootmybatis.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 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;
}
}
配置一下Druid:
package com.quan.springbootmybatis.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監控 //配置管理後臺Servlet @Bean public ServletRegistrationBean statViewServlet(){ ServletRegistrationBean bean =new ServletRegistrationBean(new StatViewServlet(),"/druid/*"); Map<String,String> initParams = new HashMap<>(); //下面的引數都是 StatViewServlet extends ResourceServlet兩個累裡面的屬性 initParams.put("loginUsername","admin"); initParams.put("loginPassword","admin"); initParams.put("allow","");//預設允許所有 initParams.put("deny","129.204.3.132"); bean.setInitParameters(initParams); return bean; } //配置一個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"); bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList("/*")); return bean; } }
可以啟動訪問一下druid資料來源有沒有起來:
註解版詳解:
編寫一個處理sql的介面:
package com.quan.springbootmybatis.mapper; import com.quan.springbootmybatis.bean.Department; import org.apache.ibatis.annotations.*; //指定這個操作資料庫的mapper @Mapper public interface DepartmentMapper { @Select("select * from department where id = #{id}") public Department getDepartmentById(Integer id); @Delete("delete from department where id = #{id}") public int deleteDeptById(Integer 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); }
其中@Mapper指定這個介面mapper介面
我們編寫一個Controller進行測試一下:‘
import com.quan.springbootmybatis.mapper.DepartmentMapper; import com.quan.springbootmybatis.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; //不過返回頁面資料直接返回json書 @RestController public class DeptController { @Autowired DepartmentMapper departmentMapper; @GetMapping("/dept/{id}") public Department getDepartment(@PathVariable("id") Integer id){ return departmentMapper.getDepartmentById(id); } //http://localhost:8080/dept/1 @GetMapping("/dept") public Department insertDept(Department department){ departmentMapper.insertDept(department); return department; } //http://localhost:8080/dept?departmentName=CCC
結果:
由於我們的id是自增主鍵,所以如果預設不設定什麼東西,是插入的時候是不會取到主鍵的值的,所以我們要進行下面的設定:
在mapper介面方法中加入多一個註解@Options
@Options(useGeneratedKeys = true,keyProperty = "id") @Insert("insert into department(departmentName) values(#{departmentName})") public int insertDept(Department department);
/* 在接口裡面加入options 是否使用自動生成的主鍵,用keyproperty指定主鍵是對應department屬性 */
結果就可以得到主鍵的值了
存在的問題1:如果資料庫的列名改為department_name 而department的屬性值一樣是departmentName不變的時候
是不能匹配到值的,這個時候我們就需要開啟自定義的mybatis配置規則
就是需要給容器中加入ConfigurationCustomizer;
所以編寫一個配置類取進行配置
@org.springframework.context.annotation.Configuration public class MybatisConfig { @Bean public ConfigurationCustomizer configurationCustomizer(){ // 匿名函式 return new ConfigurationCustomizer() { @Override public void customize(Configuration configuration) { configuration.setMapUnderscoreToCamelCase(true); } }; } }
這個只針對註解 生效的,如果是使用mapper對映檔案的就需要使用配置檔案取開啟
問題2,如果我們@mapper的數量很多的時候,我們需要每個都要加,麻煩!!!!
解決:往配置類,或者主配置類裡面註上註解@MapperScan
@MapperScan(value = "com.quan.springbootmybatis.mapper") @SpringBootApplication public class SpringbootmybatisApplication { public static void main(String[] args) { SpringApplication.run(SpringbootmybatisApplication.class, args); } }
去掉之前mapper資料夾裡面的所有@mapper
查詢結果還是一樣的;
這就是使用MapperScan批量燒苗所有的Mapper介面
###############################################################################
配置檔案版
建立兩個配置檔案:
mybatis-config.xml
EmployeeMapper.xml
建立一個介面:
package com.quan.springbootmybatis.mapper; import com.quan.springbootmybatis.bean.Employee; //無論是配置檔案還是註解版都需要將介面掃描到我們的容器中 //使用@Mapper或者@MapperScan public interface EmployeeMapper { public Employee getEmpById(Integer id); public void insertEmp(Employee employee); }
注:因為上面的註解版的時候加了@MapperScan註解了,所以這裡可以不用加
根據介面編寫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"> <!--namespace必須和mapper介面的全限定類名繫結--> <mapper namespace="com.quan.springbootmybatis.mapper.EmployeeMapper"> <!-- public Employee getEmpById(Integer id);--> <select id="getEmpById" resultType="com.quan.springbootmybatis.bean.Employee"> SELECT * FROM employee WHERE id = #{id} </select> <!-- public void insertEmp(Employee employee);--> <insert id="insertEmp"> INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId}) </insert> </mapper>
注:檔案的頭部資訊可以取官網檢視,直接百度進入mybatis
由於實體類和資料庫列的名字不一樣,一個是dId 一個是d_id
所以需要在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><!-- 配置 --> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> </configuration>
開啟駝峰模式規則
修改springboot主配置檔案:
需要讓程式知道對映檔案
核心要點就是要在springboot配置檔案當中指定mybatis著配置檔案和mapper檔案的位置:
#mybatis 全域性配置檔案的位置 mybatis: config-location: classpath:mybatis/mybatis-config.xml # mapper對映檔案的位置 mapper-locations: classpath:mybatis/mapper/*.xml
往之前的DeptControler檔案加入測試:
@Autowired EmployeeMapper employeeMapper; @GetMapping("/emp/{id}") public Employee getEmp(@PathVariable("id") Integer id){ return employeeMapper.getEmpById(id); }