三、Mybatis的OGNL表达式

本文介绍了OGNL表达式的功能及应用场景,包括参数传递、foreach和if标签的使用,并提供了具体的代码示例。此外,还详细解释了在使用if标签进行int类型判断时常见的错误及其解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

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

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

"":符号转义&quot;&quot;

给参数赋值:#{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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值