@Query returning Object instead of entity

前端 未结 2 1484
长情又很酷
长情又很酷 2020-12-18 06:03

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 CreditCenterReposi         


        
2条回答
  •  [愿得一人]
    2020-12-18 06:31

    If you want to selectively return parts of the entity, the recommended way to do so in JPA is dedicated DTO types also known as projection classes. For this particular query you'd go ahead with something like this:

    class CreditCenterExcerpt {
    
      private int id, loanId, clientId;
    
      public CreditCenterExcerpt(int id, int loadid, int clientid) { … }
    }
    

    and then use it in a way similarly to the one described by Koitoer.

    interface CrediCenterRepository implements Repository {
    
      @Query("select new ….CreditCenterExcerpt(CC.id, CC.loanId, CC.clientId) from CreditCenter CC")
      List yourSpecialQueryMethod();
    }
    

    The reason I wrote this up as a separate answer is that using the entity type itself has quite a few drawback (hence the recommendation of the separate type in the first place):

    The instances returned from a projecting query execution are detached by definition no matter whether the EntityManager is still open or not. By using a separate type for those calls, you don't accidentally create the impression that the object returned was a fully-populated and managed entity instance.

    A developer not aware of the projection might just use the instance returned, try to access properties not populated or even try to save the instance in turn and thus wipe out all the properties not loaded in the first place.

提交回复
热议问题