标签
1.sql
<sql id="user">
id,username,password
</sql>
<select>
select
<include refid="user"/>
from t_user
where id=#{id}
</select>
2.foreach
<!-- isnert:添加多条记录时,values (#{name1}),(#{name2}),(#{name3})不需要加上open和close-->
<insert id="saveTags">
INSERT IGNORE INTO tags(tagName) VALUES
<foreach collection="tags" item="tag" separator=",">
(#{tag})
</foreach>
</insert>
<select id="getTagsIdByTagName" resultType="long">
SELECT id FROM tags WHERE tagName IN
<!-- in (#{tagName1},#{tagName2},#{tagName3})需要加上open和close -->
<!-- 循环遍历 -->
<foreach collection="tagNames" item="tagName" separator="," open="(" close=")">
#{tagName}
</foreach>
</select>
3.choose-when-otherwise
<select id="getUserByNickname" resultMap="BaseResultMap">
...省略...
<!-- 条件判断 -->
<choose>
<when test="nickname!=null and nickname!=''">
and u.nickname like concat('%',#{nickname},'%') ORDER BY u.`id`
</when>
<otherwise>
ORDER BY u.`id` limit 20
</otherwise>
</choose>
</select>
4.if
where中
使用if会自动去掉前后的and
<select id="findStudentByCondition" parameterType="student">
select
<include refid="Base_Column_List"/>
<where>
<if test="id != null">
and id = #{id}
</if>
<if test="name!=null and name !=''">
and name = #{name}
</if>
<if test="age != null">
and age = #{age}
</if>
<if test="gender!=null and gender !=''">
and gender = #{gender}
</if>
</where>
</select>
update中
使用if会自动去掉前后的,
<update id="updateStudentById" parameterType="student">
update student
<set>
<if test="name!=null and name != ''">
name=#{name} ,
</if>
<if test="age!=null">
age=#{age} ,
</if>
<if test="gender!=null and gender != ''">
gender=#{gender} ,
</if>
</set>
where id = #{id}
</update>
5.collection
对于实体类中有List集合属性:
List<Role> roles;
- Property:实体类中属性的名字
- javaType:list就是list,set就是set
- ofType:集合里面的泛型类型
<collection property="roles" javaType="list" ofType="com.xxx.entity.Role">
<id column="rid" property="id">
<result column="rname" property="name">
...
</collection>
List<String> roles;
- constructor:指定构造器,里面是构造器的参数
- Arg:参数的名字
<collection property="roleList" ofType="string">
<constructor>
<arg column="role_label"/>
</constructor>
</collection>
标签属性
insert标签中的属性
- useGeneratedKeys
只针对mysql数据库有效,是否使用数据库的自动自增策略。 - keyProperty
将本次自动递增生成的值,赋值给对象的哪个属性
例子:
<insert id="xxx" useGeneratedKeys="true" keyProperty="id" parameterType="user">
</insert>
解释:使用数据库的自动递增,将自动递增的值复制给user中的id属性。