1. 程式人生 > >《Mybatis從入門到精通》讀書筆記(四)

《Mybatis從入門到精通》讀書筆記(四)

第九章. Spring整合Mybaits

MyBatis-Spring可以幫助我們將Mybaits程式碼無縫整合到Spring中。使用這個類庫中的類,Spring將會載入必要的Mybaits工廠類和Session類。這個類庫也提供了一個簡單的方式將Mybaits資料對映器和SqlSession注入到業務層的bean中,而且也可以處理事務,翻譯Mybaits的異常到Spring的DataAccessException資料訪問異常中。

applicationContext.xml
<bean id="dataSource" class="org.apache.ibatis.datasource.pooled.PooledDataSource">
    <property name="driver" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
    <property name="username" value="root"/>
    <property name="password" value=""/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <property name="dataSource" ref="dataSource"/>
    <property name="mapperLocations">
        <array>
            <value>classpath:tk/mybatis/**/mapper/*.xml</value>
        </array>
    </property>
    <property name="typeAliasesPackage" value="tk.mybatis.web.model"/>
</bean>
<!-- 這個配置不支援Ant風格的路徑,當需要配置多個包路徑時可以使用分號或逗號進行分隔。-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="addToConfig" value="true"/>
    <!-- 可以使用分號和逗號作為分隔符設定多餘一個的包路,每個對映器將會在指定的包路徑中遞迴的被搜尋到。-->
    <property name="basePackage" value="tk.mybatis.**.mapper"/>
    <!-- 用於過濾被掃描的介面,如果設定了該屬性,那麼Mybatis的介面中只有包含該註解才會被掃描進去。-->
    <!--<property name="annotationClass" value=""/>-->
</bean>
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>
        <setting name="logImpl" value="LOG4J"/>
        <setting name="cacheEnabled" value="true"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
	</settings>
</configuration>

spring-framework-bom是Spring的一個專案清單檔案,由於整合Spring時需要新增很多Spring元件的依賴,為了避免使用不同版本的元件導致意外情況發生,可以使用spring-framework-bom。新增spring-framework-bom後,在使用Spring依賴時就不需要再配置每個依賴的版本號了,Spring元件的版本由spring-framework-bom統一管理。這不僅可以避免版本混亂引起的問題。還可以很方便的升級Spring的版本。
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-framework-bom</artifactId>
            <version>4.3.4.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

第十章. Spring Boot整合Mybaits

1. pom.xml:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.2.0</version>
</dependency>
<dependency>
	<groupId>tk.mybatis</groupId>
	<artifactId>simple</artifactId>
	<version>0.0.1-SNAPSHOT</version>
</dependency>

2. 配置Spring Boot主啟動類掃描Mybatis的Mapper介面(通過@MapperScan註解)

@SpringBootApplication預設自動掃描其所在類的同級包以及子包(所以建議主啟動類放在最外層的包名下)。為了讓@SpringBootApplication掃描到simple-0.0.1-SNAPSHOT.jar中的mapper介面,需要藉助@MapperScan註解來顯示指定需要掃描的mapper包路徑。

@SpringBootApplication
@MapperScan({"tk.mybatis.springboot.mapper", "tk.mybatis.simple.mapper"})
public class Application implements CommandLineRunner {
    // 省略
}

3. 配置Spring Boot掃描Mybatis的xml對映檔案

mybatis.mapper-locations=classpath:mapper/*.xml,classpath*:tk/**/mapper/*.xml

注:為了掃描到jar包中的xml對映檔案,需要採用classpath*才能檢索到!

4. mybatis其他配置選項

Mybatis Starter提供的所有可配置的屬性都在org.mybatis.spring.boot.autoconfigure.MybatisProperties類中,該類部分程式碼如下:
@ConfigurationProperties(
    prefix = "mybatis"
)
public class MybatisProperties {
    public static final String MYBATIS_PREFIX = "mybatis";
    private String configLocation;
    private String[] mapperLocations;
    private String typeAliasesPackage;
    // 省略部分
    @NestedConfigurationProperty
    private Configuration configuration;
    // 省略部分

Spring Boot可以通過@ConfigurationProperties註解自動將配置檔案中的屬性組裝到物件上。這個註解一般都需要配置與屬性匹配的字首,此處字首為"mybatis",因此對Mybatis的配置都是以"mybatis."作為字首的。屬性類中的欄位如果是駝峰形式的,在配置檔案中進行配置時建議改為橫槓(-)和小寫字母連線的形式,雖然Spring Boot仍然能正確匹配駝峰形式的屬性。但是支援Spring Boot的IDE在自動提示時會使用標準的形式。例如configLocation在配置時應改寫成mybatis.config-location的形式。

MybatisProperties並沒有把所有的屬性都列舉出來,但是這個類提供了一個巢狀的Configuration屬性,通過這種方式可以直接對Configuration物件進行屬性配置。例如settings中的屬性可以按照下面的方式進行配置。

mybatis.configuration.lazy-loading-enabled=true
mybatis.configuration.aggressive-lazy-loading=true

基本上大部分的配置都可以通過這種形式去實現,如果遇到不會配置的內容,仍然可以通過mybatis-config.xml方式去配置Mybatis,然後在Spring Boot配置中指定該檔案的路徑即可,示例如下:

mybatis.config-location=classpath:mybaits-config.xml