更新時間:2021-06-21 12:11:12 來源:動力節(jié)點 瀏覽1139次
首先當(dāng)然得下載mybatis-3.0.5.jar和mybatis-spring-1.0.1.jar兩個JAR包,并放在WEB-INF的lib目錄下(如果你使用maven,則jar會根據(jù)你的pom配置的依賴自動下載,并存放在你指定的maven本地庫中,默認(rèn)是~/.m2/repository),前一個是mybatis核心包,后一個是和spring整合的包。
使用mybatis,必須有個全局配置文件configuration.xml,來配置mybatis的緩存,延遲加載等等一系列屬性,該配置文件示例如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
<configuration>
<settings>
<!-- 全局映射器啟用緩存 -->
<setting name="cacheEnabled" value="true" />
<!-- 查詢時,關(guān)閉關(guān)聯(lián)對象即時加載以提高性能 -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- 設(shè)置關(guān)聯(lián)對象加載的形態(tài),此處為按需加載字段(加載字段由SQL指 定),不會加載關(guān)聯(lián)表的所有字段,以提高性能 -->
<setting name="aggressiveLazyLoading" value="false" />
<!-- 對于未知的SQL查詢,允許返回不同的結(jié)果集以達(dá)到通用的效果 -->
<setting name="multipleResultSetsEnabled" value="true" />
<!-- 允許使用列標(biāo)簽代替列名 -->
<setting name="useColumnLabel" value="true" />
<!-- 允許使用自定義的主鍵值(比如由程序生成的UUID 32位編碼作為鍵值),數(shù)據(jù)表的PK生成策略將被覆蓋 -->
<setting name="useGeneratedKeys" value="true" />
<!-- 給予被嵌套的resultMap以字段-屬性的映射支持 -->
<setting name="autoMappingBehavior" value="FULL" />
<!-- 對于批量更新操作緩存SQL以提高性能 -->
<setting name="defaultExecutorType" value="BATCH" />
<!-- 數(shù)據(jù)庫超過25000秒仍未響應(yīng)則超時 -->
<setting name="defaultStatementTimeout" value="25000" />
</settings>
<!-- 全局別名設(shè)置,在映射文件中只需寫別名,而不必寫出整個類路徑 -->
<typeAliases>
<typeAlias alias="TestBean"
type="com.wotao.taotao.persist.test.dataobject.TestBean" />
</typeAliases>
<!-- 非注解的sql映射文件配置,如果使用mybatis注解,該mapper無需配置,但是如果mybatis注解中包含@resultMap注解,則mapper必須配置,給resultMap注解使用 -->
<mappers>
<mapper resource="persist/test/orm/test.xml" />
</mappers>
</configuration>
該文件放在資源文件的任意classpath目錄下,假設(shè)這里就直接放在資源根目錄,等會spring需要引用該文件。
查看ibatis-3-config.dtd發(fā)現(xiàn)除了settings和typeAliases還有其他眾多元素,比如properties,objectFactory,environments等等,這些元素基本上都包含著一些環(huán)境配置,數(shù)據(jù)源定義,數(shù)據(jù)庫事務(wù)等等,在單獨使用mybatis的時候非常重要,比如通過以構(gòu)造參數(shù)的形式去實例化一個sqlsessionFactory,就像這樣:
SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader);
SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader, properties);
SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader, environment, properties);
而typeHandlers則用來自定義映射規(guī)則,如你可以自定義將Character映射為varchar,plugins元素則放了一些攔截器接口,你可以繼承他們并做一些切面的事情,至于每個元素的細(xì)節(jié)和使用,你參考mybatis用戶指南即可。
現(xiàn)在我們用的是spring,因此除settings和typeAliases元素之外,其他元素將會失效,故不在此配置,spring會覆蓋這些元素的配置,比如在spring配置文件中指定c3p0數(shù)據(jù)源定義如下:
<!-- c3p0 connection pool configuration -->
<bean id="testDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<!-- 數(shù)據(jù)庫驅(qū)動 -->
<property name="driverClass" value="${db.driver.class}" />
<!-- 連接URL串 -->
<property name="jdbcUrl" value="${db.url}" />
<!-- 連接用戶名 -->
<property name="user" value="${db.username}" />
<!-- 連接密碼 -->
<property name="password" value="${db.password}" />
<!-- 初始化連接池時連接數(shù)量為5個 -->
<property name="initialPoolSize" value="5" />
<!-- 允許最小連接數(shù)量為5個 -->
<property name="minPoolSize" value="5" />
<!-- 允許最大連接數(shù)量為20個 -->
<property name="maxPoolSize" value="20" />
<!-- 允許連接池最大生成100個PreparedStatement對象 -->
<property name="maxStatements" value="100" />
<!-- 連接有效時間,連接超過3600秒未使用,則該連接丟棄 -->
<property name="maxIdleTime" value="3600" />
<!-- 連接用完時,一次產(chǎn)生的新連接步進(jìn)值為2 -->
<property name="acquireIncrement" value="2" />
<!-- 獲取連接失敗后再嘗試10次,再失敗則返回DAOException異常 -->
<property name="acquireRetryAttempts" value="10" />
<!-- 獲取下一次連接時最短間隔600毫秒,有助于提高性能 -->
<property name="acquireRetryDelay" value="600" />
<!-- 檢查連接的有效性,此處小弟不是很懂什么意思 -->
<property name="testConnectionOnCheckin" value="true" />
<!-- 每個1200秒檢查連接對象狀態(tài) -->
<property name="idleConnectionTestPeriod" value="1200" />
<!-- 獲取新連接的超時時間為10000毫秒 -->
<property name="checkoutTimeout" value="10000" />
</bean>
配置中的${}都是占位符,在你指定數(shù)據(jù)庫驅(qū)動打war時會自動替換,替換的值在你的父pom中配置,至于c3p0連接池的各種屬性詳細(xì)信息和用法,你自行參考c3p0的官方文檔,這里要說明的是checkoutTimeout元素,記得千萬要設(shè)大一點,單位是毫秒,假如設(shè)置太小,有可能會導(dǎo)致沒等數(shù)據(jù)庫響應(yīng)就直接超時了,小弟在這里吃了不少苦頭,還是基本功太差。
數(shù)據(jù)源配置妥當(dāng)之后,我們就要開始非常重要的sessionFactory配置了,無論是hibernate還是mybatis,都需要一個sessionFactory來生成session,sessionFactory配置如下:
<bean id="testSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:configuration.xml" />
<property name="dataSource" ref="testDataSource" />
</bean>
testSqlSessionFactory有兩處注入,一個就是前面提到的mybatis全局設(shè)置文件configuration.xml,另一個就是上面定義的數(shù)據(jù)源了(注:hibernate的sessionFactory只需注入hibernate.cfg.xml,數(shù)據(jù)源定義已經(jīng)包含在該文件中),好了,sessionFactory已經(jīng)產(chǎn)生了,由于我們用的mybatis3的注解,因此spring的sqlSessionTemplate也不用配置了,sqlSessionTemplate也不用注入到我們的BaseDAO中了,相應(yīng)的,我們需要配置一個映射器接口來對應(yīng)sqlSessionTemplate,該映射器接口定義了你自己的接口方法,具體實現(xiàn)不用關(guān)心,代碼如下:
<!-- data OR mapping interface -->
<bean id="testMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="testSqlSessionFactory" />
<property name="mapperInterface" value="com.wotao.taotao.persist.test.mapper.TestMapper" />
</bean>
對應(yīng)于sqlSessionTemplate,testMapper同樣需要testSqlSessionFactory注入,另外一個注入就是你自己定義的Mapper接口,該接口定義了操作數(shù)據(jù)庫的方法和SQL語句以及很多的注解,稍后我會講到。到此,mybatis和spring整合的文件配置就算OK了(注:如果你需要開通spring對普通類的代理功能,那么你需要在spring配置文件中加入),至于其他的如事務(wù)配置,AOP切面注解等內(nèi)容不在本文范圍內(nèi),不作累述。
至此,一個完整的myabtis整合spring的配置文件看起來應(yīng)該如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- c3p0 connection pool configuration -->
<bean id="testDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${db.driver.class}" />
<property name="jdbcUrl" value="${db.url}" />
<property name="user" value="${db.username}" />
<property name="password" value="${db.password}" />
<property name="initialPoolSize" value="5" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxStatements" value="100" />
<property name="maxIdleTime" value="3600" />
<property name="acquireIncrement" value="2" />
<property name="acquireRetryAttempts" value="10" />
<property name="acquireRetryDelay" value="600" />
<property name="testConnectionOnCheckin" value="true" />
<property name="idleConnectionTestPeriod" value="1200" />
<property name="checkoutTimeout" value="10000" />
</bean>
<bean id="testSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:configuration.xml" />
<property name="dataSource" ref="testDataSource" />
</bean>
<!-- data OR mapping interface -->
<bean id="testMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="testSqlSessionFactory" />
<property name="mapperInterface" value="com.wotao.taotao.persist.test.mapper.TestMapper" />
</bean>
<!-- add your own Mapper here -->
<!-- comment here, using annotation -->
<!-- <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> -->
<!-- <constructor-arg index="0" ref="sqlSessionFactory" /> -->
<!-- </bean> -->
<!-- base DAO class, for module business, extend this class in DAO -->
<!-- <bean id="testBaseDAO" class="com.test.dao.TestBaseDAO"> -->
<!-- <property name="sqlSessionTemplate" ref="sqlSessionTemplate" /> -->
<!-- </bean> -->
<!-- <bean id="testDAO" class="com.test.dao.impl.TestDAOImpl" /> -->
<!-- you can DI Bean if you don't like use annotation -->
</beans>
到此為止,我們只講了mybatis和spring的整合,還沒有真正觸及mybatis的核心:使用mybatis注解代替映射文件編程,通過上述內(nèi)容,我們知道配置搞定,但是testMapper還沒有被實現(xiàn),而注解的使用,全部集中在這個testMapper上,是mybatis注解的核心所在,先來看一下這個testMapper接口是個什么樣的:
/**
* The test Mapper interface.
*
* @author HuangMin <a href="mailto:minhuang@hengtiansoft.com>send email</a>
*
* @since 1.6
* @version 1.0
*
* #~TestMapper.java 2011-9-23 : afternoon 10:51:40
*/
@CacheNamespace(size = 512)
public interface TestMapper {
/**
* get test bean by UID.
*
* @param id
* @return
*/
@SelectProvider(type = TestSqlProvider.class, method = "getSql")
@Options(useCache = true, flushCache = false, timeout = 10000)
@Results(value = {
@Result(id = true, property = "id", column = "test_id", javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "testText", column = "test_text", javaType = String.class, jdbcType = JdbcType.VARCHAR) })
public TestBean get(@Param("id") String id);
/**
* get all tests.
*
* @return
*/
@SelectProvider(type = TestSqlProvider.class, method = "getAllSql")
@Options(useCache = true, flushCache = false, timeout = 10000)
@Results(value = {
@Result(id = true, property = "id", column = "test_id", javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "testText", column = "test_text", javaType = String.class, jdbcType = JdbcType.VARCHAR) })
public List<TestBean> getAll();
/**
* get tests by test text.
*
* @param testText
* @return
*/
@SelectProvider(type = TestSqlProvider.class, method = "getByTestTextSql")
@Options(useCache = true, flushCache = false, timeout = 10000)
@ResultMap(value = "getByTestText")
public List<TestBean> getByTestText(@Param("testText") String testText);
/**
* insert a test bean into database.
*
* @param testBean
*/
@InsertProvider(type = TestSqlProvider.class, method = "insertSql")
@Options(flushCache = true, timeout = 20000)
public void insert(@Param("testBean") TestBean testBean);
/**
* update a test bean with database.
*
* @param testBean
*/
@UpdateProvider(type = TestSqlProvider.class, method = "updateSql")
@Options(flushCache = true, timeout = 20000)
public void update(@Param("testBean") TestBean testBean);
/**
* delete a test by UID.
*
* @param id
*/
@DeleteProvider(type = TestSqlProvider.class, method = "deleteSql")
@Options(flushCache = true, timeout = 20000)
public void delete(@Param("id") String id);
}
下面逐個對里面的注解進(jìn)行分析:
@CacheNamespace(size = 512) : 定義在該命名空間內(nèi)允許使用內(nèi)置緩存,最大值為512個對象引用,讀寫默認(rèn)是開啟的,緩存內(nèi)省刷新時間為默認(rèn)3600000毫秒,寫策略是拷貝整個對象鏡像到全新堆(如同CopyOnWriteList)因此線程安全。
@SelectProvider(type = TestSqlProvider.class, method = "getSql") : 提供查詢的SQL語句,如果你不用這個注解,你也可以直接使用@Select("select * from ....")注解,把查詢SQL抽取到一個類里面,方便管理,同時復(fù)雜的SQL也容易操作,type = TestSqlProvider.class就是存放SQL語句的類,而method = "getSql"表示get接口方法需要到TestSqlProvider類的getSql方法中獲取SQL語句。
@Options(useCache = true, flushCache = false, timeout = 10000) : 一些查詢的選項開關(guān),比如useCache = true表示本次查詢結(jié)果被緩存以提高下次查詢速度,flushCache = false表示下次查詢時不刷新緩存,timeout = 10000表示查詢結(jié)果緩存10000秒。
@Results(value = {
@Result(id = true, property = "id", column = "test_id", javaType = String.class, jdbcType = JdbcType.VARCHAR),
@Result(property = "testText", column = "test_text", javaType = String.class, jdbcType = JdbcType.VARCHAR) }) : 表示sql查詢返回的結(jié)果集,@Results是以@Result為元素的數(shù)組,@Result表示單條屬性-字段的映射關(guān)系,如:@Result(id = true, property = "id", column = "test_id", javaType = String.class, jdbcType = JdbcType.VARCHAR)可以簡寫為:@Result(id = true, property = "id", column = "test_id"),id = true表示這個test_id字段是個PK,查詢時mybatis會給予必要的優(yōu)化,應(yīng)該說數(shù)組中所有的@Result組成了單個記錄的映射關(guān)系,而@Results則單個記錄的集合。另外還有一個非常重要的注解@ResultMap也和@Results差不多,到時會講到。
@Param("id") :全局限定別名,定義查詢參數(shù)在sql語句中的位置不再是順序下標(biāo)0,1,2,3....的形式,而是對應(yīng)名稱,該名稱就在這里定義。
@ResultMap(value = "getByTestText") :重要的注解,可以解決復(fù)雜的映射關(guān)系,包括resultMap嵌套,鑒別器discriminator等等。注意一旦你啟用該注解,你將不得不在你的映射文件中配置你的resultMap,而value = "getByTestText"即為映射文件中的resultMap ID(注意此處的value = "getByTestText",必須是在映射文件中指定命名空間路徑)。@ResultMap在某些簡單場合可以用@Results代替,但是復(fù)雜查詢,比如聯(lián)合、嵌套查詢@ResultMap就會顯得解耦方便更容易管理。
一個映射文件如下所示:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="com.wotao.taotao.persist.test.mapper.TestMapper">
<resultMap id="getByTestText" type="TestBean">
<id property="id" column="test_id" javaType="string" jdbcType="VARCHAR" />
<result property="testText" column="test_text" javaType="string" jdbcType="VARCHAR" />
</resultMap>
</mapper>
注意文件中的namespace路徑必須是使用@resultMap的類路徑,此處是TestMapper,文件中 id="getByTestText"必須和@resultMap中的value = "getByTestText"保持一致。
@InsertProvider(type = TestSqlProvider.class, method = "insertSql") :用法和含義@SelectProvider一樣,只不過是用來插入數(shù)據(jù)庫而用的。
@Options(flushCache = true, timeout = 20000) :對于需要更新數(shù)據(jù)庫的操作,需要重新刷新緩存flushCache = true使緩存同步。
@UpdateProvider(type = TestSqlProvider.class, method = "updateSql") :用法和含義@SelectProvider一樣,只不過是用來更新數(shù)據(jù)庫而用的。
@Param("testBean") :是一個自定義的對象,指定了sql語句中的表現(xiàn)形式,如果要在sql中引用對象里面的屬性,只要使用testBean.id,testBean.textText即可,mybatis會通過反射找到這些屬性值。
@DeleteProvider(type = TestSqlProvider.class, method = "deleteSql") :用法和含義@SelectProvider一樣,只不過是用來刪除數(shù)據(jù)而用的。
現(xiàn)在mybatis注解基本已經(jīng)講完了,接下來我們就要開始寫SQL語句了,因為我們不再使用映射文件編寫SQL,那么就不得不在java類里面寫,就像上面提到的,我們不得不在TestSqlProvider這個類里面寫SQL,雖然已經(jīng)把所有sql語句集中到了一個類里面去管理,但聽起來似乎仍然有點惡心,幸好mybatis提供SelectBuilder和SqlBuilder這2個小工具來幫助我們生成SQL語句,SelectBuilder專門用來生成select語句,而SqlBuilder則是一般性的工具,可以生成任何SQL語句,我這里選擇了SqlBuilder來生成,TestSqlProvider代碼如下:
/*
* #~ test-afternoon10:51:40
*/
package com.wotao.taotao.persist.test.sqlprovider;
import static org.apache.ibatis.jdbc.SqlBuilder.BEGIN;
import static org.apache.ibatis.jdbc.SqlBuilder.FROM;
import static org.apache.ibatis.jdbc.SqlBuilder.SELECT;
import static org.apache.ibatis.jdbc.SqlBuilder.SQL;
import static org.apache.ibatis.jdbc.SqlBuilder.WHERE;
import static org.apache.ibatis.jdbc.SqlBuilder.DELETE_FROM;
import static org.apache.ibatis.jdbc.SqlBuilder.INSERT_INTO;
import static org.apache.ibatis.jdbc.SqlBuilder.SET;
import static org.apache.ibatis.jdbc.SqlBuilder.UPDATE;
import static org.apache.ibatis.jdbc.SqlBuilder.VALUES;
import java.util.Map;
/**
* The test sql Provider,define the sql script for mapping.
*
* @author HuangMin <a href="mailto:minhuang@hengtiansoft.com>send email</a>
*
* @since 1.6
* @version 1.0
*
* #~TestSqlProvider.java 2011-9-23 : afternoon 10:51:40
*/
public class TestSqlProvider {
/** table name, here is test */
private static final String TABLE_NAME = "test";
/**
* get test by id sql script.
*
* @param parameters
* @return
*/
public String getSql(Map<String, Object> parameters) {
String uid = (String) parameters.get("id");
BEGIN();
SELECT("test_id, test_text");
FROM(TABLE_NAME);
if (uid != null) {
WHERE("test_id = #{id,javaType=string,jdbcType=VARCHAR}");
}
return SQL();
}
/**
* get all tests sql script.
*
* @return
*/
public String getAllSql() {
BEGIN();
SELECT("test_id, test_text");
FROM(TABLE_NAME);
return SQL();
}
/**
* get test by test text sql script.
*
* @param parameters
* @return
*/
public String getByTestTextSql(Map<String, Object> parameters) {
String tText = (String) parameters.get("testText");
BEGIN();
SELECT("test_id, test_text");
FROM(TABLE_NAME);
if (tText != null) {
WHERE("test_text like #{testText,javaType=string,jdbcType=VARCHAR}");
}
return SQL();
}
/**
* insert a test sql script.
*
* @return
*/
public String insertSql() {
BEGIN();
INSERT_INTO(TABLE_NAME);
VALUES("test_id", "#{testBean.id,javaType=string,jdbcType=VARCHAR}");
VALUES("test_text", "#{testBean.testText,javaType=string,jdbcType=VARCHAR}");
return SQL();
}
/**
* update a test sql script.
*
* @return
*/
public String updateSql() {
BEGIN();
UPDATE(TABLE_NAME);
SET("test_text = #{testBean.testText,javaType=string,jdbcType=VARCHAR}");
WHERE("test_id = #{testBean.id,javaType=string,jdbcType=VARCHAR}");
return SQL();
}
/**
* delete a test sql script.
*
* @return
*/
public String deleteSql() {
BEGIN();
DELETE_FROM(TABLE_NAME);
WHERE("test_id = #{id,javaType=string,jdbcType=VARCHAR}");
return SQL();
}
}
BEGIN();表示刷新本地線程,某些變量為了線程安全,會先在本地存放變量,此處需要刷新。
SELECT,F(xiàn)ROM,WHERE等等都是sqlbuilder定義的公用靜態(tài)方法,用來組成你的sql字符串。如果你在testMapper中調(diào)用該方法的某個接口方法已經(jīng)定義了參數(shù)@Param(),那么該方法的參數(shù)Map parameters即組裝了@Param()定義的參數(shù),比如testMapper接口方法中定義參數(shù)為@Param("testId"),@Param("testText"),那么parameters的形態(tài)就是:[key="testId",value=object1],[key="testText",value=object2],如果接口方法沒有定義@Param(),那么parameters的key就是參數(shù)的順序小標(biāo):[key=0,value=object1],[key=1,value=object2],SQL()將返回最終append結(jié)束的字符串,sql語句中的形如
#{id,javaType=string,jdbcType=VARCHAR}完全可簡寫為#{id},我只是為了規(guī)整如此寫而已。另外,對于復(fù)雜查詢還有很多標(biāo)簽可用,比如:JOIN,INNER_JOIN,GROUP_BY,ORDER_BY等等,具體使用詳情,你可以查看源碼。
最后記得把你的Mapper接口注入到你的DAO類中,在DAO中引用Mapper接口方法即可。我在BaseDAO中的注解注入如下:
......
@Repository("testBaseDAO")
public class TestBaseDAO {
......
......
/**
* @param testMapper
* the testMapper to set
*/
@Autowired
public void setTestMapper(@Qualifier("testMapper") TestMapper testMapper) {
this.testMapper = testMapper;
}
......
以上就是動力節(jié)點小編介紹的"MyBatis注解詳解",希望對大家有幫助,如有疑問,請在線咨詢,有專業(yè)老師隨時為您服務(wù)。
初級 202925
初級 203221
初級 202629
初級 203743