http://blog.csdn.net/bluesky5219/article/details/7066174
本文主要介绍Spring与Mybatis三种常用整合方法,需要的整合架包是mybatis-spring.jar,可通过链接
http://code.google.com/p/mybatis/下载到。
1、采用数据映射器(MapperFactoryBean)的方式,不用写mybatis映射文件,采用注解方式提供相应的sql语句和输入参数。
(1)Spring配置文件:
<!-- 引入jdbc配置文件 -->
<context:property-placeholder location="jdbc.properties"/>
<!--创建jdbc数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<property name="initialSize" value="${initialSize}"/>
<property name="maxActive" value="${maxActive}"/>
<property name="maxIdle" value="${maxIdle}"/>
<property name="minIdle" value="${minIdle}"/>
</bean>
<!-- 创建SqlSessionFactory,同时指定数据源-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<!--创建数据映射器,数据映射器必须为接口-->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.xxt.ibatis.dbcp.dao.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="userDaoImpl2" class="com.xxt.ibatis.dbcp.dao.impl.UserDaoImpl2">
<property name="userMapper" ref="userMapper"/>
</bean>
public class UserDaoImpl2 implements UserDao {
private UserMapper userMapper;
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
public User getUserById(User user) {
return userMapper.getUser(user.getId());
}
}
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
<!-- <property name="mapperLocations" value="classpath*:com/xxt/ibatis/dbcp/domain/user.map.xml"/ > -->
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<bean id="userDaoImpl3" class="com.xxt.ibatis.dbcp.dao.impl.UserDaoImpl3">
<!--注入SqlSessionTemplate实例 -->
<property name="sqlSessionTemplate" ref="sqlSession" />
<!--也可直接注入SqlSessionFactory实例,二者都指定时,SqlSessionFactory失效 -->
<!-- <property name="sqlSessionFactory" ref="sqlSessionFactory" />
-->
</bean>