今天特地整理了一下Spring和Mybatis的整合:
1,对应sql接口自动生成实现类
Spring配置文件添加
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.spring.mapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
自动为接口添加实现类,并有Spring容器管理,同时注意,对应的mapper配置文件,namespace要是接口的全限定名,这样配置文件就和接口绑定了。
2,和接口无关,
通过获取SqlSession,调用类似sqlSession.selectOne("com.spring.mapper.UserDao.findUserById", userId);来执行,配置文件如下:
<mapper namespace="com.spring.mapper.UserDao">
<select id="findUserById" parameterType="long" resultType="com.spring.entry.User">
select * from tbuser where userId = #{userId}
</select>
</mapper>
当然,使用数据源的话sqlSessionFactory必不可少,mybatis的配置文件和datasource作为参数生成sqlSessionFactory,并有Spring容器管理
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis的全局配置文件,放在classpath下的mybatis文件夹中了 -->
<property name="configLocation" value="SqlMapConfig.xml" />
<!-- 加载数据源,使用上面配置好的数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>