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

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

问题描述

当我对选择字段使用@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
}

推荐答案

好的,您似乎正在使用实体 CreditCenter 上的投影

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 返回对象而不是实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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