![](/img/trans.png)
[英]How to return a custom object from a Spring Data JPA GROUP BY query
[英]Spring data JPA - return an Object from a Group Query
我想知道很熱,可以通過查詢從Group返回對象。
我的存儲庫界面中有此查詢
@Query(value = "SELECT data, objectId, stampo, min(rendimento) as rendimento from rendimenti where objectId=:objectId "
+ "and stampo=:mold group By data, objectId, stampo order by data DESC LIMIT 0,1", nativeQuery = true)
Wrapper findByObjectAndMold(@Param("objectId") int objecId, @Param("mold") String mold);
該查詢應返回單個對象(或不返回),在數據庫上運行它。 我創建了一個包裝器對象以獲取結果
public class Wrapper {
@Column(name="rendimento")
private Performance performance;
private int objectId;
@Column(name="stampo")
private String mold;
@Column(name="data")
private Date date;
//getters and setters
}
我收到這個例外
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: Unknown entity: javax.persistence.Tuple; nested exception is org.hibernate.MappingException: Unknown entity: javax.persistence.Tuple] with root cause
org.hibernate.MappingException: Unknown entity: javax.persistence.Tuple
所以我認為查詢無法映射到我的包裝器...
所以我以這種方式更改了查詢方法
@Query(value = "SELECT data, objectId, stampo, min(rendimento) as rendimento from rendimenti where objectId=:objectId "
+ "and stampo=:mold group By data, objectId, stampo order by data DESC LIMIT 0,1", nativeQuery = true)
Object[] findByObjectAndMold(@Param("objectId") int objecId, @Param("mold") String mold);
然后我嘗試采用Array元素
Object[] o = repository(object.getObjectId(), mold);
logger.debug("Wrapper is " + o.toString());
if(o != null){
Date date = (Date) o[0];
logger.debug("La data è : " + date);
float performance = (float) o[3];
但是,我遇到了投放錯誤。
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.lang.Date
哪個是正確的方法?
Object[]
第一個解決方案Object[]
Entities
和/或您不能使用JPQL
則在wrapper類中創建一個構造函數,該構造函數將所有需要的參數作為Object
。
最好放置默認的非arg構造函數,因為其他一些東西可能需要它。
public Wrapper(Object o1, Object o2 ... ) { //means NOT varargs but as //many args you need, all as objects this.performance = (Performance)o1; this.id = (Integer)o2; ... }
然后,如果使用Java8
則可以使用原始Object []輕松進行Stream
轉換。
List<Wrapper> wrappers = Arrays.stream(yourObjectArray) .map( arr -> new Wrapper(arr[0], arr[1], ...)) // the rs possible args .collect(Collectors.toList());
只需檢查costructor中的args是否與查詢Object[]
所獲取的順序相同。 當然,您也可以在.map()
更改順序,但是在我看來,這只會使事情變得混亂。
NEW
public Wrapper(Performance o1, Integer o2 ... ) { //means NOT varargs but as //many args you need, all as real types they are this.performance = o1; this.id = o2; ... }
然后,就像創建JPQL TypedQuery
一樣簡單-
TypedQuery<Wrapper> tq = em.createQuery( " SELECT NEW Wrapper(E.Performance, E.id ...) FROM yourquerystuff " , Wrapper.class); List<Wrapper> wrappers = tq.getResultList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.