Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

spring - @Query returning Object instead of entity

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();
}

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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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")

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){...}
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...