MyBatis动态SQL和高级映射,如何实现查询?

摘要:动态SQL if标签 一般应用在多条件查询中 <select id="selectByMultipleCondition" resultType=&q
动态SQL if标签 一般应用在多条件查询中 <select id="selectByMultipleCondition" resultType="car" parameterType="Car"> SELECT id, car_num AS carNum, brand, guide_price AS guidePrice, produce_time AS produceTime, car_type AS carType FROM t_car WHERE 1=1 /* if标签中test属性是必须的,test属性的值是一个boolean类型的值。 只有test属性的值为true时,if标签中的SQL片段才会被拼接到最终的SQL语句中。 test属性中可以使用的是: 当使用了@Param注解:test使用的是注解指定的参数名。比如@Param(“brand”),那么只能使用brand; 若没有使用@Param注解:test使用的是arg0、arg1、param1、param2 当使用了Pojo:那么test中使用的Pojo类的属性名*/ <if test="carNum != null and carNum != ''"> AND car_num = #{carNum} </if> <if test="brand != null and brand != ''"> AND brand = #{brand} </if> <if test="carType != null and carType != ''"> AND car_type = #{carType} </if> </select> where标签 where标签的作用:让where子句更加动态智能, 所有条件都为空时,where标签保证不会生成where子句 自动去除某些条件前面多余的and或or(只能处理前面的,不能处理后面的) <select id="selectByMultipleConditionWithWhere" resultType="car" parameterType="Car"> SELECT id, car_num AS carNum, brand, guide_price AS guidePrice, produce_time AS produceTime, car_type AS carType FROM t_car <where> <if test="carNum != null and carNum != ''"> AND car_num = #{carNum} </if> <if test="brand != null and brand != ''"> AND brand = #{brand} </if> <if test="carType != null and carType != ''"> AND car_type = #{carType} </if> </where> </select> trim标签 <select id="selectByMultipleConditionWithTrim" resultType="car" parameterType="Car"> SELECT id, car_num AS carNum, brand, guide_price AS guidePrice, produce_time AS produceTime, car_type AS carType FROM t_car /* prefix:加前缀 suffix:加后缀 prefixOverrides:去掉前缀 suffixOverrides:去掉后缀 prefix="WHERE" 表示在trim标签所有你内容的前面加上WHERE关键字。 suffixOverrides="AND |OR " 表示如果trim标签中的内容以AND或者OR结尾,那么就去掉这个AND或者OR。
阅读全文