1. 程式人生 > 其它 >Mybatis-spring-boot-starter簡介

Mybatis-spring-boot-starter簡介

Mybatis-spring-boot-starter簡介

一、maven配置

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>2.5.4</version>
</dependency>

<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>

二、properties配置

spring.datasource.username=sa
spring.datasource.password=********
spring.datasource.url=jdbc:sqlserver://127.0.0.1:1433;DatabaseName=***
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver

mybatis.type-aliases-package=com.****.szxinterface.pojo.mapper
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.configuration.map-underscore-to-camel-case=true

logging.root.level=debug #顯示除錯SQL語句

@Mapper
@Repository
public interface MiningCarRunStatusMapper {
List<MineCarRunStatus> findMiningCarRunStatusS(@Param("param") String Date);
}
<mapper namespace="com.dfmc.szxinterface.mapper.MiningCarRunStatusMapper">
<select id="findMiningCarRunStatusS" parameterType="java.lang.String" resultType="com.dfmc.szxinterface.model.MineCarRunStatus">
exec sg_interface_data_truck #{param}
</select>
</mapper>

三、mybatis-spring-boot-starter

1、簡介

MyBatis-Spring-Boot-Starter類似一箇中間件,連結Spring Boot和MyBatis,構建基於Spring Boot的MyBatis人應用程式。

MyBatis-Spring-Boot-Starter 當前版本是 2.1.2,釋出於2020年3月10日

MyBatis-Spring-Boot-Starter是個整合包,因此對MyBatis、MyBatis-Spring和SpringBoot的jar包都存在依賴,如下所示:

MyBatis-Spring-Boot-StarterMyBatis-SpringSpring BootJava
2.1 2.0 (need 2.0.2+ for enable all features) 2.1 or higher 8 or higher
1.3 1.3 1.5 6 or higher

2、安裝

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>

3、快速上手

眾所周知,MyBatis的核心有兩大元件:SqlSessionFactory 和 Mapper 介面。前者表示資料庫連結,後者表示SQL對映。當我們基於Spring使用MyBatis的時候,也要保證在Spring環境中能存在著兩大元件。

MyBatis-Spring-Boot-Starter 將會完成以下功能:

1、Autodetect an existing DataSource 自動發現存在的DataSource

2、Will create and register an instance of a SqlSessionFactory passing that DataSource as an input using the SqlSessionFactoryBean 利用SqlSessionFactoryBean建立並註冊SqlSessionFactory

3、Will create and register an instance of a SqlSessionTemplate got out of the SqlSessionFactory 建立並註冊SqlSessionTemplate

4、Auto-scan your mappers, link them to the SqlSessionTemplate and register them to Spring context so they can be injected into your beans 自動掃描Mappers,並註冊到Spring上下文環境方便程式的注入使用

假設,我們有如下Mapper:

@Mapper
public interface CityMapper {

@Select("SELECT * FROM CITY WHERE state = #{state}")
City findByState(@Param("state") String state);

}

你僅僅需要建立一個Spring Boot程式讓Mapper注入即可:

@SpringBootApplication
public class SampleMybatisApplication implements CommandLineRunner {

private final CityMapper cityMapper;

public SampleMybatisApplication(CityMapper cityMapper) {
this.cityMapper = cityMapper;
}

public static void main(String[] args) {
SpringApplication.run(SampleMybatisApplication.class, args);
}

@Override
public void run(String... args) throws Exception {
System.out.println(this.cityMapper.findByState("CA"));
}

}

僅此而已,如上程式就是一個Spring Boot程式。

4、高階掃描

預設情況下,MyBatis-Spring-Boot-Starter會查詢以@Mapper註解標記的對映器。

你需要給每個MyBatis對映器標識上@Mapper註解,但是這樣非常的麻煩,這時可以使用@MapperScan註解來掃描包。

備註:關於@MapperScan註解更多的介紹,請移步這裡:http://www.mybatis.cn/archives/862.html

需要提醒的是:如果MyBatis Spring Boot Starter在Spring的上下文中至少找到一個MapperFactoryBean,那麼它將不會啟動掃描過程,因此如果你想停止掃描,那麼應該使用@Bean方法顯式註冊對映器。

標籤: none

三、mybatis中文文件

http://mybatis.org/mybatis-3/zh/dynamic_sql.html

1、動態sql語句

1.1、if

使用動態 SQL 最常見情景是根據條件包含 where 子句的一部分。比如:

<select id="findActiveBlogWithTitleLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>

這條語句提供了可選的查詢文字功能。如果不傳入 “title”,那麼所有處於 “ACTIVE” 狀態的 BLOG 都會返回;如果傳入了 “title” 引數,那麼就會對 “title” 一列進行模糊查詢並返回對應的 BLOG 結果(細心的讀者可能會發現,“title” 的引數值需要包含查詢掩碼或萬用字元字元)。

如果希望通過 “title” 和 “author” 兩個引數進行可選搜尋該怎麼辦呢?首先,我想先將語句名稱修改成更名副其實的名稱;接下來,只需要加入另一個條件即可。

<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</select>

1.2、choose、when、otherwise

有時候,我們不想使用所有的條件,而只是想從多個條件中選擇一個使用。針對這種情況,MyBatis 提供了 choose 元素,它有點像 Java 中的 switch 語句。

還是上面的例子,但是策略變為:傳入了 “title” 就按 “title” 查詢,傳入了 “author” 就按 “author” 查詢的情形。若兩者都沒有傳入,就返回標記為 featured 的 BLOG(這可能是管理員認為,與其返回大量的無意義隨機 Blog,還不如返回一些由管理員精選的 Blog)。

<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>

1.3、trim、where、set

前面幾個例子已經方便地解決了一個臭名昭著的動態 SQL 問題。現在回到之前的 “if” 示例,這次我們將 “state = ‘ACTIVE’” 設定成動態條件,看看會發生什麼。

<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</select>

如果沒有匹配的條件會怎麼樣?最終這條 SQL 會變成這樣:

SELECT * FROM BLOG
WHERE

這會導致查詢失敗。如果匹配的只是第二個條件又會怎樣?這條 SQL 會是這樣:

SELECT * FROM BLOG
WHERE
AND title like ‘someTitle’

這個查詢也會失敗。這個問題不能簡單地用條件元素來解決。這個問題是如此的難以解決,以至於解決過的人不會再想碰到這種問題。

MyBatis 有一個簡單且適合大多數場景的解決辦法。而在其他場景中,可以對其進行自定義以符合需求。而這,只需要一處簡單的改動:

<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>

where 元素只會在子元素返回任何內容的情況下才插入 “WHERE” 子句。而且,若子句的開頭為 “AND” 或 “OR”,where 元素也會將它們去除。

如果 where 元素與你期望的不太一樣,你也可以通過自定義 trim 元素來定製 where 元素的功能。比如,和 where 元素等價的自定義 trim 元素為:

<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>

prefixOverrides 屬性會忽略通過管道符分隔的文字序列(注意此例中的空格是必要的)。上述例子會移除所有 prefixOverrides 屬性中指定的內容,並且插入 prefix 屬性中指定的內容。

用於動態更新語句的類似解決方案叫做 setset 元素可以用於動態包含需要更新的列,忽略其它不更新的列。比如:

<update id="updateAuthorIfNecessary">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</set>
where id=#{id}
</update>

這個例子中,set 元素會動態地在行首插入 SET 關鍵字,並會刪掉額外的逗號(這些逗號是在使用條件語句給列賦值時引入的)。

來看看與 set 元素等價的自定義 trim 元素吧:

<trim prefix="SET" suffixOverrides=",">
...
</trim>

注意,我們覆蓋了字尾值設定,並且自定義了字首值。

1.4、foreach

動態 SQL 的另一個常見使用場景是對集合進行遍歷(尤其是在構建 IN 條件語句的時候)。比如:

<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>

foreach 元素的功能非常強大,它允許你指定一個集合,宣告可以在元素體內使用的集合項(item)和索引(index)變數。它也允許你指定開頭與結尾的字串以及集合項迭代之間的分隔符。這個元素也不會錯誤地新增多餘的分隔符,看它多智慧!

提示 你可以將任何可迭代物件(如 List、Set 等)、Map 物件或者陣列物件作為集合引數傳遞給 foreach。當使用可迭代物件或者陣列時,index 是當前迭代的序號,item 的值是本次迭代獲取到的元素。當使用 Map 物件(或者 Map.Entry 物件的集合)時,index 是鍵,item 是值。

至此,我們已經完成了與 XML 配置及對映檔案相關的討論。下一章將詳細探討 Java API,以便你能充分利用已經建立的對映配置。

1.5、script

要在帶註解的對映器介面類中使用動態 SQL,可以使用 script 元素。比如:

  @Update({"<script>",
"update Author",
" <set>",
" <if test='username != null'>username=#{username},</if>",
" <if test='password != null'>password=#{password},</if>",
" <if test='email != null'>email=#{email},</if>",
" <if test='bio != null'>bio=#{bio}</if>",
" </set>",
"where id=#{id}",
"</script>"})
void updateAuthorValues(Author author);

1.6、bind

bind 元素允許你在 OGNL 表示式以外建立一個變數,並將其繫結到當前的上下文。比如:

<select id="selectBlogsLike" resultType="Blog">
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
SELECT * FROM BLOG
WHERE title LIKE #{pattern}
</select>

四、文件

https://github.com/mybatis/spring-boot-starter