当前位置: 首页 > 工具软件 > Dao Script > 使用案例 >

MyBatis之if判断(Script)

司马自明
2023-12-01

mybatis 映射文件中,if标签判断字符串相等与否

  • 方式一,判断相等【加.toString()转换成字符串】
<if test="remark != null and remark != ''and auditidentified =='2'.toString()">
  ,refusalreason=#{remark,jdbcType=VARCHAR}
</if>
  • 方式二,判断相等【单引号,里面套双引号】
<if test='remark != null and remark != "" and auditidentified =="2"'>
  ,refusalreason=#{remark,jdbcType=VARCHAR}
</if>

错误方式

<if test="remark != null and remark != ''and auditidentified =='2'">
   ,refusalreason=#{remark,jdbcType=VARCHAR}
</if>

原因:mybatis是用OGNL表达式来解析的,在OGNL的表达式中,’2’会被解析成字符,java是强类型的,char 和一个string 会导致不等,所以if标签中的sql不会被解析。

Script:

@Select("<script>" +
            "select * from user " +
            "<where>" +
            "<if test=\"age != null\"> age = #{age}</if>" +
            "</where>" +
            "</script>")
List<User> getUser4(@Param("age") Integer age);

@Select({"<script>"
			+ "SELECT COUNT(1) FROM table where 1=1"
			+"<if test='keyword != null and keyword!=\"\"'>"
			+ "AND ( API_CODE LIKE #{keyword} OR API_NAME LIKE #{keyword})</if>"
			+"<if test='apiMenuStatus != null and apiMenuStatus !=\"\"'>"
			+"AND STATUS = #{apiMenuStatus}</if>"
			+"</script>"})
	public int sizeByLike(@Param("keyword")String keyword,@Param("apiMenuStatus")String apiMenuStatus);
	

感谢:https://blog.csdn.net/thebigdipperbdx/article/details/82526819
https://blog.csdn.net/thebigdipperbdx/article/details/82526819

 类似资料: