Spring集成Mybatis3
阿新 • • 發佈:2017-06-21
添加 stat font rec set ans tno eth lose
否則直接加入jar包 mybatis-spring-1.2.1.jar到build path以及 WEB-INF/lib目錄
spring和mybatis原有的jar包還是必須的哦。
使用 MyBatis-Spring的一個主要原因就是允許MyBatis使用Spring的事務管理,MyBatis-Spring 利用Spring現有的DataSourceTransactionManager 來管理事務 標準配置: 啟用spring事務管理,只需要配置這個bean:
0 說明
Mybatis使用 MyBatis-Spring 類庫來集成spring框架
MyBatis-Spring官網 http://www.mybatis.org/spring/index.html MyBatis-Spring是一個MyBatis框架的子模塊,可以提供和Spring框架的無縫集成。它可以是Mybatis利用Spring來實現事務管理,使用IOC機制管理MyBatis的 映射和sql會話對象(SqlSession), 把Mybatis異常轉換為Spring的DataAccessException。 不同的Mybatis和Spring需要的 mybatis-spring版本MyBatis-Spring | MyBatis | Spring |
---|---|---|
1.0.0 and 1.0.1 | 3.0.1 to 3.0.5 | 3.0.0 or higher |
1.0.2 | 3.0.6 | 3.0.0 or higher |
1.1.0 or higher | 3.1.0 or higher | 3.0.0 or higher |
1.3.0 or higher | 3.4.0 or higher | 3.0.0 or higher |
1 添加依賴
如果用了maven,則添加
<dependency>
<groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.1</version> </dependency>
2 基本配置
在Spring中使用Mybatis最少要在Spring 中配置兩個東西:一個SqlSessionFactory 和至少一個映射接口
在MyBatis-Spring中, 一個 SqlSessionFactoryBean 用來創建 SqlSessionFactory ,要配置這個工程bean,在spring xml配置文件中加入以下內容:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
註意 SqlSessionFactory 需要依賴一個 DataSource . 此 DataSource 可以是任意的Spring中配置的數據源連接配置。
假定你有了一個這樣定義的接口映射:
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{userId}")
User getUser(@Param("userId") String userId);
}
那麽這個接口要在Spring中的聲明需要配置為 MapperFactoryBean 的實例:
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
註意這個映射類必須是一個接口,而不是一個實際的實現類。在這個例子中,我們使用註解方式來指定SQL,當然也可以使用MyBatis的XML配置文件。
一旦配置好以後,就可以將映射直接註入到需要使用的業務/服務對象中,方法和其他spring bean的註入方式一樣。
MapperFactoryBean 工廠類負責 SqlSession 的創建和關閉。如果當前線程處於Spring管理的事務中,會話會在事務完成時提交或回滾。最後,所有異常都會被轉化Spring DataAccessExceptions.
調用MyBatis 數據訪問方法現在只需要一行代碼:
public class FooServiceImpl implements FooService {
private UserMapper userMapper;
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
public User doSomeBusinessStuff(String userId) {
return this.userMapper.getUser(userId);
}
3 事務管理
使用 MyBatis-Spring的一個主要原因就是允許MyBatis使用Spring的事務管理,MyBatis-Spring 利用Spring現有的DataSourceTransactionManager 來管理事務 標準配置: 啟用spring事務管理,只需要配置這個bean:
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
The DataSource 對應的數據源可以使 JDBC的 DataSource 也可以是支持連接池的數據源或者JNDI方式管理的數據源。
註意指定這個DataSource 也同時是用來為SqlSessionFactoryBean 連接數據庫的數據源,這樣事務管理才能生效。
<!-- 啟動聲明式事務 -->
<tx:annotation-driven transaction-manager="transactionManager"/><!-- a PlatformTransactionManager is still required -->
Java代碼:
// the service class that we want to make transactional
@Transactional
public class DefaultFooService implements FooService {
Foo getFoo(String fooName);
Foo getFoo(String fooName, String barName);
void insertFoo(Foo foo);
void updateFoo(Foo foo);
}
AOP方式配置事務屬性,需要事務管理器
<tx:advice id="txAdvice" transaction-manager="txManager">
<!-- the transactional semantics... -->
<tx:attributes>
<!-- all methods starting with ‘get‘ are read-only -->
<tx:method name="get*" read-only="true"/>
<!-- other methods use the default transaction settings (see below) -->
<tx:method name="insert*"/> <tx:method name="update*"/>
</tx:attributes>
</tx:advice>
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="updateStock" no-rollback-for="InstrumentNotFoundException" iolation="DEFAULT" propagation="REQUIRED" />
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
來源: http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#transaction-declarative-txadvice-settings
* 編程方式使用事務:
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status = txManager.getTransaction(def);
try {
userMapper.insertUser(user);
}
catch (MyException ex) {
txManager.rollback(status);
throw ex;
}
txManager.commit(status);
來源: http://www.mybatis.org/spring/transactions.html
註意SqlSession.commit(), SqlSession.rollback() or SqlSession.close() 這些 SqlSession.的事務方法都不能使用。否則會收到 UnsupportedOperationException 異常。這些方法在這裏都不可見。
設置傳播行為和隔離級別:
配置方式:
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" isolation="DEFAULT" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
註解方式:
@Transactional(readOnly = true) public class DefaultFooService implements FooService { public Foo getFoo(String fooName) { // do something } // these settings have precedence for this method @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public void updateFoo(Foo foo) { // do something } }
Spring集成Mybatis3