@Query returns an object instead of an object

When I use the @Query annotation with select fields, I do not return the object of the object. How can I return an object of an object?

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 cause any errors, but when I try to iterate, it throws a classcastexception

List<CreditCenter> objects = findAllIds();
for (CreditCenter cc : objects) { //This line throws ClassCastException
    //some logic
}
+4
source share
2 answers

Well it seems that you are using a projection over a CreditCenter object

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

My first thought: Why aren't you using something like this.

 @Query("SELECT CC FROM CreditCenter CC")

which will return a list of objects, however, probably you do not want to return all fields, so my second tip is using this query.

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

Creditcenter, . JPQL jpa repos, .

public class CreditCenter {

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

, JPA - DTO, . :

class CreditCenterExcerpt {

  private int id, loanId, clientId;

  public CreditCenterExcerpt(int id, int loadid, int clientid) { … }
}

, Koitoer.

interface CrediCenterRepository implements Repository<CreditCenter, Integer> {

  @Query("select new ….CreditCenterExcerpt(CC.id, CC.loanId, CC.clientId) from CreditCenter CC")
  List<CreditCenterExcerpt> yourSpecialQueryMethod();
}

, , , ( ):

, , , EntityManager . , , .

, , , , , , , , .

+1

Source: https://habr.com/ru/post/1536883/


All Articles