JPA : How to convert a native query result set to POJO class collection

后端 未结 21 1504
孤街浪徒
孤街浪徒 2020-11-22 09:23

I am using JPA in my project.

I came to a query in which I need to make join operation on five tables. So I created a native query which returns five fields.

21条回答
  •  名媛妹妹
    2020-11-22 09:31

    If you use Spring-jpa, this is a supplement to the answers and this question. Please correct this if any flaws. I have mainly used three methods to achieve "mapping result Object[] to a pojo" based on what practical need I meet:

    1. JPA built in method is enough.
    2. JPA built in method is not enough, but a customized sql with its Entity are enough.
    3. The former 2 failed, and I have to use a nativeQuery. Here are the examples. The pojo expected:

      public class Antistealingdto {
      
          private String secretKey;
      
          private Integer successRate;
      
          // GETTERs AND SETTERs
      
          public Antistealingdto(String secretKey, Integer successRate) {
              this.secretKey = secretKey;
              this.successRate = successRate;
          }
      }
      

    Method 1: Change the pojo into an interface:

    public interface Antistealingdto {
        String getSecretKey();
        Integer getSuccessRate();
    }
    

    And repository:

    interface AntiStealingRepository extends CrudRepository {
        Antistealingdto findById(Long id);
    }
    

    Method 2: Repository:

    @Query("select new AntistealingDTO(secretKey, successRate) from Antistealing where ....")
    Antistealing whatevernamehere(conditions);
    

    Note: parameter sequence of POJO constructor must be identical in both POJO definition and sql.

    Method 3: Use @SqlResultSetMapping and @NamedNativeQuery in Entity as the example in Edwin Dalorzo's answer.

    The first two methods would call many in-the-middle handlers, like customized converters. For example, AntiStealing defines a secretKey, before it is persisted, a converter is inserted to encrypt it. This would result in the first 2 methods returning a converted back secretKey which is not what I want. While the method 3 would overcome the converter, and returned secretKey would be the same as it is stored (an encrypted one).

提交回复
热议问题