繁体   English   中英

当 select 参数之一为 null 时,mybatis select 查询未返回结果

[英]mybatis select query is not returning result when one of the select parameters is null

我需要一些关于 Mybatis/Java 的帮助。

我的映射器中有以下 select :

 <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 列的值为 null。 我使用“utrn is null”子句在数据库上触发相同的查询并返回该行。 但是上面的代码没有返回该行。 其他参数的值是正确的。 当我为 utrn 字段传入一个有效值时,代码工作正常。

当 utrn 参数为 null 时,知道如何让 mybatis 生成 UTRN 为 null?

谢谢你!

之所以如此,是因为如果没有设置值,您的 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 语法,以防第一个是 null 并被忽略。

如果你有更多条件,你可以在 mybatis 中使用when ,它可以有很多条件,1 个默认条件用于任何其他情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM