mybatis配置方式有很多,这里做个简单记录applicationContext-mybatis.xml文件如下
<bean id="sqlSessionFactory-source" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dynamicDataSource" />
<property name="mapperLocations" value="classpath:conf/mybatis/xxxx/*-mapper.xml" />
</bean>
<!-- scan for mappers and let them be autowired -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xxx.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory-source" />
</bean>
根据配置可以看出SqlSessionFactoryBean配置数据源和mapper的xml文件所在位置,MapperScannerConfigurer用来配置扫描基础目录以及引入SqlSessionFactoryBeanName
下面是mapper.xml的例子
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xx.dao.AssetsFlowMapper">
<resultMap id="assetsFlowMap" type="com.xx.api.bean.zz">
<result property="debtId" column="debt_id"/>
<result property="userId" column="user_id"/>
</resultMap>
<!-- 插入数据 -->
<insert id="addAssetsFlow" parameterType="com.bean.AssetsFlow">
<selectKey resultType="int" order="AFTER"
keyProperty="flowId">
SELECT LAST_INSERT_ID() AS id
</selectKey>
INSERT INTO t_uls_assets_flow
(debt_id,user_id)
VALUES
(#{debtId},#{userId})
</insert>
<!-- 更新数据 -->
<update id="updateAssetsFlow" parameterType="com.bean.AssetsFlow">
UPDATE t_uls_assets_flow
<set>
<if test="debtId != null">
debt_id=#{debtId},
</if>
<if test="userId != null">
user_id=#{userId},
</if>
</set>
WHERE flow_id = #{flowId}
</update>
<!-- 搜索条件 -->
<sql id="selectWhere">
<where>
<if test="debtId != null">
AND debt_id=#{debtId}
</if>
<if test="userId != null">
AND user_id=#{userId}
</if>
</where>
</sql>
<!-- 数据总量 -->
<select id="getxxxCount" resultType="int" parameterType="Map">
SELECT count(1)
FROM
xxxx
<include refid="selectWhere"></include>
</select>
</mapper>
接下来就是
AssetsFlowMapper接口写上相应的方法,使用@Repository注入即可使用
当然基本的注解扫描,组件扫描必不可少
<context:component-scan base-package="com.xxx.*"/>