要spring 和mybatis 一起使用,至少需要要在spring 应用上下文中定义两个东西 第一: SqlSessionFactory 和至少一个数据映射器类(或者映射文件)
1)如果使用数据映射类 :springContext.xml中的配置
<!-- 声明annotation配置 -->
<context:annotation-config />
<bean id="userMapper" class="org.mybatis.spring.MapperFactoryBean">
<property name="mapperInterface" value="cn.com.edu.dao.mapper.UserMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
数据映射类:
public interface UserMapper {
@Select("SELECT * FROM huai_user WHERE userId=#{userId}")
User getUserById(@Param("userId") int userId);
}
2)如果使用映射文件
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mapperLocations" value="classpath*:cn/com/edu/dao/mapper/**/*.xml"></property> </bean>
3) 注意信息:
一旦配置好,你可以用注入其它任意 Spring 的 bean 相同的方式直接注入映射器到你的
business/service 对象中。MapperFactoryBean处理 SqlSession的创建和关闭它。如果使用
了 Spring 的事务,那么当事务完成时,session 将会提交或回滚。最终,任何异常都会被翻
译成 Spring 的 DataAccessException异常。
在基本的mybatis中,session工厂可以由SqlSessionFactoryBuilder来创建,但是在mybatis-spring 中,用 sqlSessionFactoryBean替代。在一般的 MyBatis-Spring 用法中,你不需要直接使用 SqlSessionFactoryBean或 和其对的 SqlSessionFactory。相反,session 工厂将会被注入到 MapperFactoryBean或其它扩
了 SqlSessionDaoSupport的 DAO(