mybatis的标签
<where>与<if>结合使用,那么and将不受影响
更新语句时,防止逗号的多余<if>结合<set>使用
<trim>更灵活的去除多余的关键字,可实现where和set的功能
<select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap"> SELECT * from STUDENT_TBL ST <trim prefix="WHERE" prefixOverrides="AND|OR"> <if test="studentName!=null and studentName!='' "> ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%') </if> <if test="studentSex!= null and studentSex!= '' "> AND ST.STUDENT_SEX = #{studentSex} </if> </trim> </select>
update id="updateStudent" parameterType="StudentEntity"> UPDATE STUDENT_TBL <trim prefix="SET" suffixOverrides=","> <if test="studentName!=null and studentName!='' "> STUDENT_TBL.STUDENT_NAME = #{studentName}, </if> <if test="studentSex!=null and studentSex!='' "> STUDENT_TBL.STUDENT_SEX = #{studentSex}, </if> <if test="studentBirthday!=null "> STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday}, </if> <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' "> STUDENT_TBL.CLASS_ID = #{classEntity.classID} </if> </trim> WHERE STUDENT_TBL.STUDENT_ID = #{studentID}; </update>
choose (when, otherwise)
!-- 查询学生list,like姓名、或=性别、或=生日、或=班级,使用choose --> <select id="getStudentListChooseEntity" parameterType="StudentEntity" resultMap="studentResultMap"> SELECT * from STUDENT_TBL ST <where> <choose> <when test="studentName!=null and studentName!='' "> ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%') </when> <when test="studentSex!= null and studentSex!= '' "> AND ST.STUDENT_SEX = #{studentSex} </when> <when test="studentBirthday!=null"> AND ST.STUDENT_BIRTHDAY = #{studentBirthday} </when> <when test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' "> AND ST.CLASS_ID = #{classEntity.classID} </when> <otherwise> </otherwise> </choose> </where> </select>
if是与(and)的关系,而choose是或(or)的关系,从多个选项中选择一个。
foreach:
<select id="getStudentListByClassIDs" resultMap="studentResultMap"> SELECT * FROM STUDENT_TBL ST WHERE ST.CLASS_ID IN <foreach collection="list" item="classList" open="(" separator="," close=")"> #{classList} </foreach> </select>