我一直在尋找,但沒有找到我的問題的答案。
我有以下代碼:
public ScriptInfo findByForeignKey(int id) {
Session currentSession = entityManager.unwrap(Session.class);
Query<ScriptInfo> theQuery =
currentSession.createQuery("Select *
from SCRIPT_INF AND SPRINT
where FK_ID_SPRINT=:idSprint
AND FK_ID_SPRINT=SPRINT.ID_SPRINT");
theQuery.setParameter("idSprint", id);
}
我不知道如何放置回傳值,因此它回傳ScriptInfo過濾后的物件。
uj5u.com熱心網友回復:
Query 提供了多種方法來獲取查詢結果:
getResultList()getFirstResult()getSingleResult()
正確的選擇取決于您的期望和想要回傳的內容。它們各自的行為在 的JavaDoc 中Query有描述。為了讓它們正常作業,您需要通過將其添加為引數來提供您希望查詢回傳哪個類的資訊createQuery
您的最終代碼看起來與此有些類似:
public ScriptInfo findByForeignKey(int id) {
Query<ScriptInfo> theQuery = entityManager.createQuery("select si from ScriptInfo si where si.sprint.id = :idSprint", ScriptInfo.class);
theQuery.setParameter("idSprint", id);
return theQuery.getFirstResult();
}
注 1:
您使用createQuerywhich 需要 HQL 或 JPQL 查詢,但您傳入的似乎是 SQL。這行不通。使用createSQLQuery()或者使用 JPQL。我推薦后者,因為我認為當您無法使用 JPQL 表達查詢時,您應該只回退到 SQL。當您需要轉換方面的幫助時,請隨意創建一個新問題。只需確保包含您的域模型。
筆記2:
你并不需要unwrap的Session從EntityManager。您在 中使用的所有功能Session也可在EntityManager. 僅createSQLQuery名為createNativeQuery.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/358237.html
