动态sql
1. 例如: 分页查询 当传入start和size 时,按照传入的参数分页查询,如果没有传入时,查询全部数据
<select id="queryPage" resultMap="resultBaseScore" parameterType="com.example.mybatis1.domain.Score">
-- 如果着两个参数不为空,就查询start 和size
select * from score
<if test="start !=null and size != null">
limit #{start},#{size}
</if>
</select>
2 例如:
<select id="queryparam" resultMap="resultBaseScore" parameterType="com.example.mybatis1.domain.Score">
select * from score
<where>
<if test="sNO !=null and sNo!='' ">
and s_no=#{sNo}
</if>
<if test="cNo !=null and cNo!='' ">
and c_No=#{cNo}
</if>
</where>
</select>
3 set
<update id="updataStudent" parameterType="com.example.mybatis1.domain.Student">
updata student
<set>
<if test="sname!=null and sname!='' ">
sname=#{sname},
</if>
<if test="sage!=null and sage!='' ">
sage=#{age}
</if>
</set>
</update>
4 trim 可以代替where 和set
select * from score
<trim prefix="where" prefixOverrides="and ">
<if test="sNo !=null and sNo !='' ">
and s_no = #{sNo}
</if>
<if test="cNO !=null and cNo !='' ">
and c_no =#{cNo}
</if>
</trim>
5 foreach 批量插入,批量查询 注意 一定要写 @param 1 #{ 这是java中的字段}
<select id="getBooksByIds" parameterType="com.example.mybatis1.domain.Student">
select * from student where id in
<foreach collection="sNos" open="(" close=")" separator=",">
#{sNo}
</foreach>
</select>
2 批量插入
<insert id="batchAddStudent">
insert into student sname,sage values
<foreach collection="students" separator="," item="student">
(#{student.sname},#{student.sage})
</foreach>
</insert>
|