如何动态查询?
当我没有接触到mybatis的时候一般的条件查询就是通过后台来判断参数分别执行不同的sql语句来得到我们想要的数据(反正我个人是这个样子的,不知道你们是不是这个样子啊),从刚开始对着mybatis的用户手册开始的时候到后来对动态条件查询的描述,个人感觉就是在配置文件中帮你进行动态的拼接sql语句,mybatis提供了很多有用的标签,比如<if>、<where>、<foreach>等等一系列你可以想到的标签,接下来我就不写实例了,直接贴一个配置文件的动态条件查询吧(很简单的一种)
<!--
2 if(判断参数) - 将实体类不为空的属性作为where条件 -->
<select id=
"getStudentList_if" resultMap=
"resultMap_studentEntity" parameterType=
"liming.student.manager.data.model.StudentEntity">
SELECT
ST.STUDENT_ID,
ST.STUDENT_NAME,
ST.STUDENT_SEX,
ST.STUDENT_BIRTHDAY,
ST.STUDENT_PHOTO,
ST.CLASS_ID,
ST.PLACE_ID
FROM STUDENT_TBL
ST
WHERE
<if test=
"studentName !=null ">
ST.STUDENT_NAME LIKE CONCAT(CONCAT(
'%',
#{studentName, jdbcType=VARCHAR}),'%')
</if>
<if test=
"studentSex != null and studentSex != '' ">
AND ST.STUDENT_SEX =
#{studentSex, jdbcType=INTEGER}
</if>
<if test=
"studentBirthday != null ">
AND ST.STUDENT_BIRTHDAY =
#{studentBirthday, jdbcType=DATE}
</if>
<if test=
"classId != null and classId!= '' ">
AND ST.CLASS_ID =
#{classId, jdbcType=VARCHAR}
</if>
<if test=
"classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">
AND ST.CLASS_ID =
#{classEntity.classId, jdbcType=VARCHAR}
</if>
<if test=
"placeId != null and placeId != '' ">
AND ST.PLACE_ID =
#{placeId, jdbcType=VARCHAR}
</if>
<if test=
"placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">
AND ST.PLACE_ID =
#{placeEntity.placeId, jdbcType=VARCHAR}
</if>
<if test=
"studentId != null and studentId != '' ">
AND ST.STUDENT_ID =
#{studentId, jdbcType=VARCHAR}
</if>
</select>
注解:其实上面的动态条件查询的配置文件还是有点问题的,比如说studentName 的值为空的时候动态拼接的sql语句就是where and 连在一起了对不对,这个时候拼接出来的sql语句就会有错误了,那么这个时候应该怎么办呢? 其实很简单,mybatis提供了一个有用的标签解决这个问题,你们可以自己去找下,这里我就不多说了,交给你们自己去发现了。
转载请注明原文地址: https://ju.6miu.com/read-1296604.html