[英]how to write this query using jpa criteria api?
Select c.id, (Select c2.value from customer_table c2 Where c2.id = c.id And c2.key = 'test') as "test", (Select c2.value from customer_table c2 Where c2.id = c.id And c2.key = 'service-category') as "service-category", (Select c2.value from customer_table c2 Where c2.id = c.id And c2.key = 'exam') as "exam" From customer_table c Group By c.id;
假設 customerTable 實體存在並正確建模,其關系和該值是 String 類型,實現將如下所示:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<YourPojo> cq = cb.createQuery(YourPojo.class);
Root<CustomerTable> root = cq.from(CustomerTable.class);
//Subquery 1
Subquery<String> sqVal1 = cq.subquery(String.class);
Root<CustomerTable> sq1Root = sqVal1.from(CustomerTable.class);
sqVal1.where(
cb.and(
cb.equal(root.get("id"),sq1Root.get("id")),
cb.equal(sq1Root.get("key"),"test")
)
);
sqVal1.select(sq1Root.get("value"));
//Subquery 2
Subquery<String> sqVal2 = cq.subquery(String.class);
Root<CustomerTable> sq2Root = sqVal2.from(CustomerTable.class);
sqVal2.where(
cb.and(
cb.equal(root.get("id"),sq2Root.get("id")),
cb.equal(sq2Root.get("key"),"service-category")
)
);
sqVal2.select(sq2Root.get("value"));
//Subquery 3
Subquery<String> sqVal3 = cq.subquery(String.class);
Root<CustomerTable> sq3Root = sqVal3.from(CustomerTable.class);
sqVal3.where(
cb.and(
cb.equal(root.get("id"),sq3Root.get("id")),
cb.equal(sq3Root.get("key"),"exam")
)
);
sqVal3.select(sq3Root.get("value"));
cq.groupBy(root.get("id"));
cq.multiselect(
root.get("id"),
sqVal1.getSelection(),
sqVal2.getSelection(),
sqVal3.getSelection()
);
您需要一個帶有與 multiselect 子句具有相同參數(按順序和類型)的構造函數的 pojo
public class YourPojo {
public YourPojo(String id, String val1, String val2, String val3){
[...]
}
}
建議使用元模型來訪問實體的屬性,這會導致替換以下代碼
root.get("id");
與這個其他
root.get(CustomerTable_.id);
在不深入主題的情況下使用元模型的眾多優勢之一是能夠自動完成屬性名稱並減少此時出錯的機會。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.