Spring Boot(三)——Spring Boot資料訪問
一、簡介
對於資料訪問層,無論是SQL還是NOSQL,Spring Boot預設採用整合Spring Data的方式進行統一處理,新增大量自動配置,遮蔽了很多設定。引入各種xxxTemplate,xxxRepository來簡化我們對資料訪問層的操作。對我們來說只需要進行簡單的設定即可。下面來說一下在Spring Boot中如何使用MyBaits與JPA進行資料訪問。
二、配置自定義資料來源
spring-boot-starter-jdbc
預設使用tomcat-jdbc資料來源,如果想使用其他的資料來源,比使用阿里巴巴的資料池管理。在使用druid資料來源時,應該額外新增以下依賴:
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
1)編寫yml檔案
spring: datasource: # 資料來源基本配置 username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/crud 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
2)新建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.110.110"); 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; } }
三、Spring Boot中如何整合MyBatis
1)新增依賴
這裡需要新增mybatis-spring-boot-starter依賴跟mysql依賴。
<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.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
這裡不引入spring-boot-starter-jdbc依賴,是由於mybatis-spring-boot-starter中已經包含了此依賴。
MyBatis-Spring-Boot-Starter依賴將會提供如下:
- 自動檢測現有的DataSource
- 將建立並註冊SqlSessionFactory的例項,該例項使用SqlSessionFactoryBean將該DataSource作為輸入進行傳遞
- 將建立並註冊從SqlSessionFactory中獲取的SqlSessionTemplate的例項。
- 自動掃描您的mappers,將它們連結到SqlSessionTemplate並將其註冊到Spring上下文,以便將它們注入到您的bean中。
就是說,使用了該Starter之後,只需要定義一個DataSource即可(application.yml中可配置),它會自動建立使用該DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。會自動掃描你的Mappers,連線到SqlSessionTemplate,並註冊到Spring上下文中。
2)配置資料來源(同上)
3)Mybatis整合
註解方式
Mybatis註解的方式比較簡單,只要定義一個dao介面,然後sql語句通過註解寫在介面方法上。最後給這個介面新增 @Mapper註解 或者在啟動類上或者配置類上新增 @MapperScan(“要掃描的包名”) 註解即可。
@Component
@Mapper
public interface LearnMapper {
@Insert("insert into learn_resource(author, title,url) values(#{author},#{title},#{url})")
int add(LearnResouce learnResouce);
@Update("update learn_resource set author=#{author},title=#{title},url=#{url} where id = #{id}")
int update(LearnResouce learnResouce);
@DeleteProvider(type = LearnSqlBuilder.class, method = "deleteByids")
int deleteByIds(@Param("ids") String[] ids);
@Select("select * from learn_resource where id = #{id}")
@Results(id = "learnMap", value = {
@Result(column = "id", property = "id", javaType = Long.class),
@Result(property = "author", column = "author", javaType = String.class),
@Result(property = "title", column = "title", javaType = String.class)
})
LearnResouce queryLearnResouceById(@Param("id") Long id);
@SelectProvider(type = LearnSqlBuilder.class, method = "queryLearnResouceByParams")
List<LearnResouce> queryLearnResouceList(Map<String, Object> params);
class LearnSqlBuilder {
public String queryLearnResouceByParams(final Map<String, Object> params) {
StringBuffer sql =new StringBuffer();
sql.append("select * from learn_resource where 1=1");
if(!StringUtil.isNull((String)params.get("author"))){
sql.append(" and author like '%").append((String)params.get("author")).append("%'");
}
if(!StringUtil.isNull((String)params.get("title"))){
sql.append(" and title like '%").append((String)params.get("title")).append("%'");
}
System.out.println("查詢sql=="+sql.toString());
return sql.toString();
}
//刪除的方法
public String deleteByids(@Param("ids") final String[] ids){
StringBuffer sql =new StringBuffer();
sql.append("DELETE FROM learn_resource WHERE id in(");
for (int i=0;i<ids.length;i++){
if(i==ids.length-1){
sql.append(ids[i]);
}else{
sql.append(ids[i]).append(",");
}
}
sql.append(")");
return sql.toString();
}
}
}
@MapperScan(basePackages = {"com.cxxx.guns.modular.*.dao"})
public class SingleDataSourceConfig {
需要注意的是,簡單的語句只需要使用@Insert、@Update、@Delete、@Select這4個註解即可,但是有些複雜點需要動態SQL語句,就比如上面方法中根據查詢條件是否有值來動態新增sql的,就需要使用@InsertProvider、@UpdateProvider、@DeleteProvider、@SelectProvider等註解。
這些可選的 SQL 註解允許你指定一個類名和一個方法在執行時來返回執行 允許建立動態 的 SQL。 基於執行的對映語句, MyBatis 會例項化這個類,然後執行由 provider 指定的方法. 該方法可以有選擇地接受引數物件.(In MyBatis 3.4 or later, it’s allow multiple parameters) 屬性: type,method。type 屬性是類。method 屬性是方法名。
註解方式如何配置mybaits全域性配置檔案,如開啟駝峰命名
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
@Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
XML配置方式
xml配置方式保持對映檔案的老傳統,優化主要體現在不需要實現dao的是實現層,系統會自動根據方法名在對映檔案中找對應的sql,具體操作如下:
1)新建mybaits的全域性配置檔案
<?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>
2)修改application.yml 配置檔案
mybatis:
# 指定全域性配置檔案位置
config-location: classpath:mybatis/mybatis-config.xml
# 指定sql對映檔案位置
mapper-locations: classpath:mybatis/mapper/*.xml
3)編寫Dao層的程式碼
新建LearnMapper介面,無需具體實現類。
@Mapper
public interface LearnMapper {
int add(LearnResouce learnResouce);
int update(LearnResouce learnResouce);
int deleteByIds(String[] ids);
LearnResouce queryLearnResouceById(Long id);
public List<LearnResouce> queryLearnResouceList(Map<String, Object> params);
}
4)新增LearnMapper的對映檔案
在mapper目錄下新建LearnMapper.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.dudu.dao.LearnMapper">
<resultMap id="baseResultMap" type="com.dudu.domain.LearnResouce">
<id column="id" property="id" jdbcType="BIGINT" />
<result column="author" property="author" jdbcType="VARCHAR"/>
<result column="title" property="title" jdbcType="VARCHAR"/>
<result column="url" property="url" jdbcType="VARCHAR"/>
</resultMap>
<sql id="baseColumnList" >
id, author, title,url
</sql>
<select id="queryLearnResouceList" resultMap="baseResultMap" parameterType="java.util.HashMap">
select
<include refid="baseColumnList" />
from learn_resource
<where>
1 = 1
<if test="author!= null and author !=''">
AND author like CONCAT(CONCAT('%',#{author,jdbcType=VARCHAR}),'%')
</if>
<if test="title != null and title !=''">
AND title like CONCAT(CONCAT('%',#{title,jdbcType=VARCHAR}),'%')
</if>
</where>
</select>
<select id="queryLearnResouceById" resultMap="baseResultMap" parameterType="java.lang.Long">
SELECT
<include refid="baseColumnList" />
FROM learn_resource
WHERE id = #{id}
</select>
<insert id="add" parameterType="com.dudu.domain.LearnResouce" >
INSERT INTO learn_resource (author, title,url) VALUES (#{author}, #{title}, #{url})
</insert>
<update id="update" parameterType="com.dudu.domain.LearnResouce" >
UPDATE learn_resource SET author = #{author},title = #{title},url = #{url} WHERE id = #{id}
</update>
<delete id="deleteByIds" parameterType="java.lang.String" >
DELETE FROM learn_resource WHERE id in
<foreach item="idItem" collection="array" open="(" separator="," close=")">
#{idItem}
</foreach>
</delete>
</mapper>
參考文章
構建第一個Spring Boot2.0應用之配置Druid資料庫連線池
Spring Boot乾貨系列:(八)資料儲存篇-SQL關係型資料庫之JdbcTemplate的使用
Spring Boot乾貨系列:(九)資料儲存篇-SQL關係型資料庫之MyBatis的使用