[英]How can I populate parameters map with result set in MyBatis
我正在讀一本書“MyBatis in Practice”,但無法理解為什么第67-68頁的代碼不起作用。 這是問題所在。 它是關於調用存儲過程並且它可以工作,但真正的問題是我無法弄清楚如何使用結果集填充輸入映射。 所以這是主類的代碼:
public void callReadAllPets() throws Exception {
HashMap<String, List<PetDVO>> inputMap = new HashMap<String, List<PetDVO>>();
List<PetDVO> petList = new ArrayList<PetDVO>();
inputMap.put("petData", petList);
//
getSqlSession().selectList("callReadAllPets", inputMap);
List<PetDVO> outputData = inputMap.get("petData");
printResultList(outputData, "read_all_pets");
}
private void printResultList(List<PetDVO> list) {
for (PetDVO item : list) {
System.out.println(" owner: " + item.getOwner());
System.out.println(" species: " + item.getSpecies());
System.out.println(" sex: " + item.getSex());
}
}
PetDVO只是Java POJO。 這是mapper.xml中的代碼
<select id="callReadAllPets" resultType="PetDVO" statementType="CALLABLE">
CALL read_all_pets('SELECT name, owner, species, sex, birth, death FROM pet')
運行之前的代碼后,outputData列表為空,即未填充結果。 這是本書中建議的方式,但它對我不起作用? 我怎么解決這個問題? ps我正在使用MyBatis 3.2.3
好吧,如果你想用存儲過程的OUT參數填充輸入參數,你會這樣做......
<mapper namespace="com.example.SomeMapper">
<select id="doSomething" statementType="CALLABLE" parameterType="com.example.SomeRequest">
{ call someProcedure (
#{someParameter,javaType=Long,jdbcType=NUMERIC,mode=IN},
#{out,javaType=Long,jdbcType=NUMERIC,mode=OUT})
}
</select >
</mapper>
你的com.example.SomeRequest
類看起來像這樣......
class SomeRequest {
private Long someParameter;
private Long out;
// add Getters & Setters
}
這應該允許您從SomeRequest.out
變量中檢索(長)結果。 要映射更復雜的結果,您需要將它們定義為ResultSet並提供ResultMap,例如...
#{out,javaType=java.sql.ResultSet,jdbcType=CURSOR,resultMap=someResultMap,mode=OUT}
至少,這就是我們使用Oracle數據庫和包函數的方式。 希望它也能以同樣的方式與MySql存儲過程一起工作......
謝謝你的回答,但我正在使用H2。 H2中沒有存儲過程,只有存儲函數實際上是普通的Java方法。 在這種情況下,存儲的函數將返回ResultSet並直接使用查詢'SELECT name, owner, species, sex, birth, death FROM pet'
的查詢直接調用此函數會產生正確的結果。 因此,我相信MyBatis知道生成的ResultSet但無法將其放回inputMap中。 為了澄清這個問題,我會做兩件事。 首先,我要檢查resultMap="petData" will work instead of resultType="PetDVO"
,因為petData已經是inputMap的一個參數。 如果這不起作用,我將向自己保證MyBatis正在使用前面提到的方法List<PetDVO> outputData = getSqlSession().selectList("callReadAllPets", inputMap)
接收結果集。 不幸的是,幾小時后我就可以試試了。 再次感謝@Florian Schaetz。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.