@Query返回Object而不是实体 [英] @Query returning Object instead of entity

查看:173
本文介绍了@Query返回Object而不是实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在选择字段中使用@Query注释时,我没有得到实体对象。如何获取实体对象?

When I use @Query annotation with select fields, I dont get the entity object back. How can I get the entity object back?

public interface CreditCenterRepository extends JpaRepository<CreditCenter, Long> {
    @Query("SELECT CC.id, CC.loanId, CC.clientId FROM CreditCenter CC")
    List<CreditCenter> findAllIds();
}

当我从控制器调用此方法时,它不会抛出任何错误,但是,当我尝试迭代它时抛出classcastexception

When I call this method from my controller, it does not throw any error, but, when I try to iterate it throws classcastexception

List<CreditCenter> objects = findAllIds();
for (CreditCenter cc : objects) { //This line throws ClassCastException
    //some logic
}


推荐答案

好的看来您正在使用实体信贷中心投影

Ok It seems that you are using a projection over the entity CreditCenter

@Query("SELECT CC.id, CC.loanId, CC.clientId FROM CreditCenter CC")

我的第一个想法是:
为什么你不使用这样的东西。

My first thought is : Why you dont use something like this.

 @Query("SELECT CC FROM CreditCenter CC")

将返回实体列表,但可能是你不想返回所有字段,所以我的第二个建议是使用此查询。

that will return the list of the entities, however probably you dont want to return all the fields so my second advice is use this query.

@Query("SELECT new package.to.CreditCenter(CC.id, CC.loanId, CC.clientId) FROM CreditCenter CC")

并添加Creditcenter中的构造函数,支持参数的顺序和类型。这将使用JPQL和jpa repos使用它应该工作。

and add a constructor in Creditcenter that support the order and type of parameters. That will work using JPQL and as jpa repos use that it should work.

public class CreditCenter {

 //Member vars
 public CreditCenter (int id, int loadid, int clientid){...}
}

这篇关于@Query返回Object而不是实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆