Spring整合Mybatis

今天特地整理了一下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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值