TypedQuery對應的Criteria API用法如下。本例中將原本欄位改名,因此由Tuple資料結構取出資料須用別名(alias):query = em.createQuery( "SELECT e.name, e.salary FROM Employee e", Tuple.class);
@Test
public void Criteria_Tuple() {
EntityManager em = emf.createEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery sql = cb.createTupleQuery();
Root emp = sql.from(Employee.class);
sql.multiselect(
emp.get(Employee_.name).alias("employeeName"),
emp.get(Employee_.salary).alias("salary") );
TypedQuery typedQuery = em.createQuery(sql);
List resultList = typedQuery.getResultList();
// get data by alias
for (Tuple tuple : resultList) {
String employeeName = tuple.get("employeeName", String.class);
Double salary = tuple.get("salary", Double.class);
System.out.println(employeeName + "_" + salary);
}
em.close();
// validate result
List stringList = resultList.stream()
.map(t -> t.get("employeeName", String.class) + "_" +
t.get("salary", Double.class))
.collect(Collectors.toList());
assertThat(stringList,containsInAnyOrder("Jim_3000.0",
"Rose_4000.0",
"Denise_1500.0",
"Mike_2000.0"));
}
說明:
- 行5:
CriteriaQuery物件指定使用Tuple型態封裝複數欄位的查詢結果。
- 行8:
欄位name的別名使用alias()方法設定為"employeeName"。
- 行9:
欄位salary的別名使用alias()方法設定為"salary"。
- 行10:
TypedQuery物件同時指定型態為Tuple,後續所有物件若使用泛型者皆同。
- 行14-15:
Tuple型態物件使用get()方法取出需指定名稱(別名)和型態:
tuple.get("employeeName", String.class);
tuple.get("salary", Double.class);
沒有留言:
張貼留言