Mybatis-Spring

本文介绍如何将MyBatis与Spring框架整合,包括安装配置、定义SqlSessionFactory及Mapper接口,并实现简单的事务处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考文章:http://www.mybatis.org/spring/index.html


Getting Started

This chapter will show you in a few steps how to install and setup MyBatis-Spring and how to build a simple transactional application.

Installation

To use the MyBatis-Spring module, you just need to include the mybatis-spring-1.3.1.jar file and its dependencies in the classpath.

If you are using Maven just add the following dependency to your pom.xml:

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>1.3.1</version>
</dependency>

Quick Setup

To use MyBatis with Spring you need at least two things defined in the Spring application context: an SqlSessionFactory and at least one mapper interface.

In MyBatis-Spring, an SqlSessionFactoryBean is used to create an SqlSessionFactory . To configure the factory bean, put the following in the Spring XML configuration file:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
</bean>

Notice that the SqlSessionFactory requires a DataSource . This can be any DataSource and should be configured just like any other Spring database connection.

Assume you have a mapper interface defined like the following:

public interface UserMapper {
  @Select("SELECT * FROM users WHERE id = #{userId}")
  User getUser(@Param("userId") String userId);
} 

This interface is added to Spring using a MapperFactoryBean like the following:

<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>

Note that the mapper class specified must be an interface, not an actual implementation class. In this example, annotations are used to specify the SQL, but a MyBatis mapper XML file could also be used.

Once configured, you can inject mappers directly into your business/service objects in the same way you inject any other Spring bean. The MapperFactoryBean handles creating an SqlSession as well as closing it. If there is a Spring transaction in progress, the session will also be committed or rolled back when the transaction completes. Finally, any exceptions will be translated into Spring DataAccessExceptions.

Calling MyBatis data methods is now only one line of code:

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);
}


总体配置如下:
<!-- 主库数据源(JNDI方式) -->
<!--<jee:jndi-lookup id="dataSourceMaster" jndi-name="jdbc/pur_RW" proxy-interface="javax.sql.DataSource" lookup-on-startup="false" /> -->

<!-- 主库数据源 -->
<bean id ="dataSourceMaster" class= "com.mchange.v2.c3p0.ComboPooledDataSource"
	 destroy-method= "close">
	 <property name ="driverClass" value= "${master.jdbc.driverClassName}" />
	 <property name ="jdbcUrl" value="${master.jdbc.url}" />
	 <property name ="user" value="${master.jdbc.username}" />
	 <property name ="password" value="${master.jdbc.password}" />
	 <property name ="minPoolSize" value="${master.minPoolSize}" />
	 <property name ="maxPoolSize" value="${master.maxPoolSize}" />
	 <property name ="maxIdleTime" value="${master.maxIdleTime}" />
	 <property name ="acquireIncrement" value= "${master.acquireIncrement}" />
	 <property name ="maxStatements" value= "${master.maxStatements}" />
	 <property name ="initialPoolSize" value= "${master.initialPoolSize}" />
	 <property name ="idleConnectionTestPeriod" value= "${master.idleConnectionTestPeriod}" />
	 <property name ="acquireRetryAttempts" value= "${master.acquireRetryAttempts}" />
	 <property name ="breakAfterAcquireFailure" value= "${master.breakAfterAcquireFailure}" />
	 <property name ="testConnectionOnCheckout" value= "${master.testConnectionOnCheckout}" />
</bean >
<!-- 从库数据源 -->
<bean id ="dataSourceSlave" class= "com.mchange.v2.c3p0.ComboPooledDataSource"
	 destroy-method= "close">
	 <property name ="driverClass" value= "${slave.jdbc.driverClassName}" />
	 <property name ="jdbcUrl" value="${slave.jdbc.url}" />
	 <property name ="user" value="${slave.jdbc.username}" />
	 <property name ="password" value="${slave.jdbc.password}" />
	 <property name ="minPoolSize" value="${slave.minPoolSize}" />
	 <property name ="maxPoolSize" value="${slave.maxPoolSize}" />
	 <property name ="maxIdleTime" value="${slave.maxIdleTime}" />
	 <property name ="acquireIncrement" value= "${slave.acquireIncrement}" />
	 <property name ="maxStatements" value= "${slave.maxStatements}" />
	 <property name ="initialPoolSize" value= "${slave.initialPoolSize}" />
	 <property name ="idleConnectionTestPeriod" value= "${slave.idleConnectionTestPeriod}" />
	 <property name ="acquireRetryAttempts" value= "${slave.acquireRetryAttempts}" />
	 <property name ="breakAfterAcquireFailure" value= "${slave.breakAfterAcquireFailure}" />
	 <property name ="testConnectionOnCheckout" value= "${slave.testConnectionOnCheckout}" />
</bean >
  
<!-- 配置sqlSessionFactory工厂 -->
<bean id ="sqlSessionFactory" class= "org.mybatis.spring.SqlSessionFactoryBean" >
	<property name ="dataSource" ref="dataSource" />
	<property name ="mapperLocations" value= "classpath*:config/app/mybatis/*/*.xml" />
	<property name ="configLocation" value= "classpath:config/spring/mybatis-config.xml" />
</bean >

<!-- 注解方式使用SQL必须做如下配置 -->
<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
	<property name="mapperInterface" value="XX.dao.UserDao"></property>
	<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>


<!-- Spring事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource" />
</bean>
<tx:advice id ="txAdvice" transaction-manager="transactionManager">
		 <tx:attributes >
			   <tx:method name ="get*" read-only="true" />
			   <tx:method name ="set*" read-only="true" />
			   <tx:method name ="query*" read-only="true" />
			   <tx:method name ="find*" read-only="true" />
			   <tx:method name ="load*" read-only="true" />
			   <tx:method name ="count*" read-only="true" />
			   <tx:method name ="save*" rollback-for="Exception" />
			   <tx:method name ="add*" rollback-for="Exception" />
			   <tx:method name ="update*" rollback-for="Exception" />
			   <tx:method name ="delete*" rollback-for="Exception" />
			   <tx:method name ="merage*" rollback-for="Exception" />
			   <tx:method name ="updateOccupyIsolation" propagation= "REQUIRES_NEW" rollback-for ="Exception"/>
			   <tx:method name ="queryStockRoundListDetailForOccupy" propagation= "NOT_SUPPORTED" />
		 </tx:attributes >
  </tx:advice >
	  
	
	  
<!-- 采用spring与mybatis整合的第二种方法 -->
<bean id ="sqlSessionTemplate" class= "org.mybatis.spring.SqlSessionTemplate" >
	 <constructor-arg index ="0" ref="sqlSessionFactory" />
</bean >

<!-- 扫描所有mapper -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
  <property name="basePackage" value="xx.core.mapper;yy.log.mapper;" />
</bean>






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值