2013-10-25 56 views
0

我有一個hashMap參數,其中包含<Sting,Value>現在我想將這些值傳遞到兩個JPA列。如何將哈希映射作爲參數傳遞給JPA?

SELECT obj from x obj where x.no=?<String goes here> and x.amount=?<value goes here > 

我該如何使用JPQL做到這一點?

+0

鍵將事先知道,或者您想遍歷映射來執行所有鍵值對的查詢? –

+0

@DebojitSaikia我想遍歷映射來執行所有鍵值對的查詢。 – VijayM

回答

0

有了這個循環中,您可以通過Map迭代爲所有鍵值對執行select statements

Query query = em.createQuery("SELECT obj from x obj where x.no=:x_no and x.amount=:x_amt"); 
List<ResultObj> resultList = new ArrayList<ResultObj>(); 
Iterator<Entry<String, Value>> iter = yourMap.entrySet().iterator(); 
while (iter.hasNext()) { 
    Entry<String, Value> next = iter.next(); 
    Value value = next.getValue(); 
    query.setParameter("x_no", next).setParameter("x_amt", value); 
    ResultObj result = (ResultObj) query.getSingleResult(); 
    resultList.add(result); 
} 
+0

有此行'(ResultObj)query.getSingleResult();'在循環中可能會連接更多的數據庫權利? – VijayM

+0

我不明白!對於每個'x_no'和'x_amount',你將有不同的'ResultObj'。這是你想要的..對嗎? –

+0

我需要它作爲列表從給定的參數,我希望連接在DB一次(我的散列圖不會超過1000個值) – VijayM

0

to this,您可以使用鍵()和()的值,並在你的情況,它會給這樣的:

Query query = em.createQuery("SELECT obj from x obj where x.no=KEY(:mapParam) and x.amount=VALUE(:mapParam)"); 
query.setParamters("mapParam", yourMap); 
query.getResultList(); 

不過要小心,你需要在JPA 2.0,並且出現了一些問題,Hibernate的,因爲時間是固定的,不過,你必須要對一個固定版本(4.1.4+)。請參閱this

相關問題