我想知道从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);这个查询应该返回一个对象(或者没有),在DB上运行它。我创建了一个包装对象来获取结果。
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);然后我试着用数组元素
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哪一种方法是正确的?
发布于 2017-10-28 20:35:01
操纵Object[]的第一个解决方案
如果您的表或包装器不是Entities和/或不能使用JPQL,那么在包装器类中创建一个将所有需要的参数作为Object的构造函数。
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()内部的顺序,但在我看来,它只会把事情搞砸。
第二个解决方案使用JPA NEW
要求所有相关表和包装器都是实体,而且JPQL是可用的。再次为包装器创建构造函数,但现在使用真正的类型,因此不再进行强制转换。
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();https://stackoverflow.com/questions/46993227
复制相似问题