在實際的開發當中,經常需要根據不同條件拼接SQL語句
常用的動態SQL元素包括
if,choose(when,otherwise,where,set,foreach,bind
1.if
<mapper namespace="org.taohan.online.exam.dao"
resultType="org.taohan.online.StudentInfo">
select * from tb_student where state='ACTIVE'
<!--可選條件,如果傳進來的參數里面有id屬性則加入id查詢條件-->
<if test="id!=null">
and id=#{id}
</if>
<select>
</mapper>
如果有多個可選條件使用and來連接‘
<if test="id!=null" and lognname!=null>
and id=#{id} and loginname=#{loginname}
</if>
利用map傳入值
有如下數據接口
public List<StudentInfo> getStudents(Map<String, Object> map);
對應的實現如下
<!-- 獲取學生集合 --> <select id="getStudents" parameterMap="getStudentParameterMap" resultMap="queryStudent"> </select>
加入多表連接
<!--多表連接-->
SELECT a.*,b.className, c.gradeName FROM StudentInfo a INNER JOIN ClassInfo b ON a.classId=b.classId INNER JOIN GradeInfo c ON b.gradeId=c.gradeId
加入動態查詢
通過map傳入數據
StudentInfo student = new StudentInfo();
if (studentId != null)
student.setStudentId(studentId);
if (classId != null) {
classInfo.setClassId(classId);
student.setClassInfo(classInfo);
}
if (gradeId != null) {
grade.setGradeId(gradeId);
student.setGrade(grade);
}
存入集合中
map.put("student", student);//學生對象
map.put("startIndex", startIndex);//默認是0
map.put("pageShow", pageShow);//默認是10
測試
<!-- mybatis動態查詢 -->
<where>
<if test="studentId != null">
studentId=#{studentId}
</if>
<if test="classInfo != null">
<if test="classInfo.classId != null">
b.classId=#{classInfo.classId}
</if>
</if>
<if test="grade != null">
<if test="grade.gradeId != null">
c.gradeId=#{grade.gradeId}
</if>
</if>
</where>
<!-- 傳入的map數據 -->
<if test="startIndex != null and pageShow != null">
LIMIT #{startIndex}, #{pageShow}
</if>
2.choose(when,otherwise)
有時候,我們不想用所有的條件語句,而只是只想從中選擇一個,mybatis提供choose,類似於switch語句
<mapper namespace="org.taohan.online.exam.dao" >
<select id="query" resultType="org.taohan.online.StudentInfo"> select * from tb_student where state='ACTIVE' <!--如果傳入了id,就根據id查詢,如果傳入了loginname和password就根據這些來查詢,如果都沒有就使用性別為男性來查找--> <choose>
<when test="id!=null">
and id=#{id}
</when>
<when test="loginname!=null and password!=null">
and loginname=#{loginname} and password=#{password}
</when>
<otherwise>
and sex='男'
</otherwise> </choose>
</select> </mapper>
3.where
<mapper namespace="org.taohan.online.exam.dao"
resultType="org.taohan.online.StudentInfo">
select * from tb_student
<where>
<if test="state!=null">
state=#{state}
</if>
<if test="id!=null">
and id=#{id}
</if>
</where>
<select>
</mapper>
where元素知道只有一個以上的if條件有值的情況下才去插入where子句,若有“AND"或者"OR"開頭,則where元素也會去將他們刪除
4.set
<update id="update">
update tb_user
<set>
<if test="loginname!=null">
loginname=#{login}
</if>
<if test="password!=null">
password=#{password}
</if>
</set>
where id=#{id}
</update>
set元素會動態設置前置的set關鍵字,同時也會消除無關的逗號
5.foreach
6.bind
<select >
<bind name="pattern" value="'%"+_parameter.getName()+‘%’"/>
select * from tb_user
where loginname like #{pattern}
</select>
從OGNL表達式中創建一個變量並將其綁定在上下文
select * from tb_user where loginname like '%_Parameter.getName()%'
