- 添加依赖
添加mybatis-spring会将mybatis代码无缝整合到spring,引入mybatis-spring的jar包<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>x.x.x</version> </dependency>
- sessionfactory
在spring的上下文中定义sessionfactory<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" />
这里还需一个datasource,一个mapperlocation。datasource是配置数据源,mapperLocation是配置用到的mybatis的mapper文件路径
<property name="mapperlocation"><list></list></ property >
</bean>
- dao层
dao可以不写实现类,只写一个接口。配置如下:
<bean id="smsDAO" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.myyule.room.dao.RoomDao" />
<property name="sqlSessionFactory" ref="openfireSqlSessionFactory" />
</bean> 事务
配置事务管理,可使用spring的声明式事务管理
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>
<tx:annotation-driven transaction-manager=” transactionManager”>
使用@Transactional注解可以在类上面也可以在方法上面,在类上面代表这个类的所有方法都需要事务。动态sql
mybais的强大特性之一就是动态sql- if
<select id="findActiveBlogWithTitleLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <if test="title != null"> AND title like #{title} </if> </select>
- choose、when、otherwise
<select id="findActiveBlogWithTitleLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <if test="title != null"> AND title like #{title} </if> </select>
- trim
<insert id="insert" parameterType="ActivityAffix" useGeneratedKeys="true" keyProperty="affixId">
insert into myyule_activity_affix
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="affixId != null" >
affix_id,
</if>
<if test="activityId != null" >
activity_id,
</if>
<if test="type != null" >
type,
</if>
<if test="createTime != null" >
create_time,
</if>
<if test="value != null" >
value,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="affixId != null" >
#{affixId,jdbcType=BIGINT},
</if>
<if test="activityId != null" >
#{activityId,jdbcType=BIGINT},
</if>
<if test="type != null" >
#{type,jdbcType=INTEGER},
</if>
<if test="createTime != null" >
#{createTime,jdbcType=TIMESTAMP},
</if>
<if test="value != null" >
#{value,jdbcType=LONGVARCHAR},
</if>
</trim>
</insert>
- foreach
- if
and song_id in
<foreach item="item" index="index" collection="songIds"
open="(" separator="," close=")">
#{item}
</foreach>