0
点赞
收藏
分享

微信扫一扫

三、Mybatis的OGNL表达式

(一)OGNL表达式简介
功能:OGNL表达式主要用于参数值的传递,以及“foreach”、“if”等标签的使用
三、Mybatis的OGNL表达式_转义
三、Mybatis的OGNL表达式_转义_02
注意:

OGNL直接支持java中的方法(只支持JDK中的方法,不支持其他JAR包中的方法)。

例: <if test="Command != null and !"".equals(Command.trim())">and command=#{Command}</if>

&&:符号转义&& 或者 and

"":符号转义""

给参数赋值:#{command}是由mybaits处理的,遇到#{},mybaits会自动替换为?
//<foreach>标签使用实例
<foreach collection="list" item="message" separator=",">
#{message.id}
</foreach>
备注:
collection只能取上图的几个值“list/array/_parameter”;
item代表遍历到的当前项
separator代表在后面跟上“,”,同时去掉最后一个多余的“,”

(二)OGNL表达式易错点
1.在使用<if>时,注意在对”int”型对象判断时,不仅要判断是否为“null”,还得判断是否为“0”:
例:

public class Content implements Serializable {
private int id;
private int commandId;
private String content;
}
Content content = new Content();
content.setCommandId(Integer.parseInt(id));

//此时的Content对象是这样的,id被默认赋值为0了
Content content = new Content(0, commandId, null);

//此时若sql语句如下
<if test="id != null">
AND id = #{id}
</if>
<if test="commandId != null">
AND command_id = #{commandId}
</if>
//这两条sql语句都将被执行(而我们的本意是执行后面一条)

//解决办法,更改sql语句如下
<if test="id != null and id !=0">
AND id = #{id}
</if>
<if test="commandId != null and commandId !=0">
AND command_id = #{commandId}
</if>


举报

相关推荐

EL 表达式:${表达式}

0 条评论