我需要一些关于 Mybatis/Java 的帮助。
我的映射器中有以下选择:
<select id="findTxnByBusinessKey" parameterType="map" resultType="data.Transaction">SELECT
t.id, *MANY OTHER FIELDS NOT SHOWN HERE* FROM txns t
where source=#{source} and userid=#{userid} and transactiontype=#{transactiontype} and ordernumber=#{ordernumber} and utrn=#{utrn}
</select>
以下是我检索交易的 Java 代码:
HashMap keys = new HashMap();
keys.put("userid", userid);
keys.put("source", source);
keys.put("ordernumber", ordernumber);
keys.put("transactiontype", transactiontype);
keys.put("utrn", null); <--- *****SEE THIS LINE********
//keys.put("utrn", "1234"); <--- WORKS FINE
Transaction t = session.selectOne("findTxnByBusinessKey", keys);
return t;
我知道数据库中有一行,其中 urtn 列的值为空。我使用“utrn is null”子句在数据库上触发相同的查询,并返回该行。但是上面的代码没有返回那一行。其他参数的值是正确的。当我为 utrn 字段传递有效值时,代码工作正常。
知道如何让mybatis在utrn参数为null时生成UTRN为null吗?
谢谢!
答案 0 :(得分:0)
之所以如此,是因为如果没有设置值,您的 SQL 语句将不正确。您需要使用 if 子句调整您的语句并测试参数。所以你在这里做的是创建一个动态 SQL 语句。
您需要更改如下语句:
<select id="findTxnByBusinessKey"
resultType="data.Transaction">
SELECT t.id, .... FROM txns t
WHERE source=#{source}
<if test="userid != null">
AND userid=#{userid}
</if>
<if test="userid == null">
AND userid IS NULL
</if>
...
</select>
请确保必需的参数首先是名称,因为 "... where and userid=..."
将是不正确的 sql 语法,如果第一个参数为空并被忽略。
如果你有更多的条件,你可以在 mybatis 中使用 when
,它可以有很多条件,1 个默认用于任何其他情况。