簡體   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