【问题标题】:How to get @Query( nativeQuery=true) result into List<MyObject>?如何将@Query(nativeQuery=true) 结果放入 List<MyObject>?
【发布时间】:2018-06-27 22:02:48
【问题描述】:

您好,我有一个查询,我希望将结果放入对象列表中,而不是实体。但结果实际上是一个我应该转移到我的对象的对象。有没有办法将它直接映射到我的自定义对象?

【问题讨论】:

    标签: sql spring spring-data-jpa


    【解决方案1】:

    也许这会对你有所帮助:

    public interface ObjRepository extends JpaRepository<MyObject, Long> {
    
            @Query(value = "FROM MyObject WHERE objname = ?1")
            public List<MyObject> findByName(String name); 
        }
    

    【讨论】:

    • 我也在做同样的事情,但来自另一个界面。我没有仅用于我的方法的接口。结果不是我的对象列表,而是对象列表
    【解决方案2】:

    方法一:使用对象数组列表。

    当使用原生查询时,我们得到对象数组的列表,即列表中的每一行都是数组。数组中的元素表示列值。 在 repo 界面中:

    @Query(value = "select col1, col2, col3 from table1 where col1 = :key", nativeQuery = true)
    List<Object[]> findByKey(@Param("key") String key);
    

    在调用者中

    List<Object[]> objectList = new ArrayList<Object[]>();
    objectList = repo.findByKey(key);
        List<CustomObject> customObjectList = new ArrayList<>();
        for (Object[] tuple : objectList) {
            String col1 = (String) tuple[0];
            String col2 = (String) tuple[1];
            String col3 = (String) tuple[2];
    
            CustomObject obj = new CustomObject();
            obj.setCol1(col1);
            obj.setCol2(col2);
            obj.setCol3(col3);
            customObjectList.add(obj);
        }
        return customObjectList;
    

    方法 2:使用表示每行中的列的自定义 dto。

    参考https://stackoverflow.com/a/42905382/1358551

    【讨论】:

      【解决方案3】:
              final List<MyCustomDTO> statuses = myRepository
                  .findStatuses(marketId, campaignId, stationIds).stream()
                  .map(o -> new MyCustomDTO(((BigInteger) o[0]), (Boolean) o[1], (Timestamp) o[2]))
                  .collect(toList());
      
      
      
      public class StationStatusDTO {
      
          private long id;
          private boolean isSomething;
          private LocalDateTime date;
      
          public MyCustomDTO(BigInteger id, Boolean isSomething, Timestamp date) {
              this(id.longValue(),
                  isSomething,
                  (date == null) ? null : LocalDateTime
                      .ofInstant(Instant.ofEpochMilli(date.getTime()),
                          TimeZone.getDefault().toZoneId()));
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-10
        • 1970-01-01
        • 2020-11-26
        • 2011-11-25
        • 1970-01-01
        • 2016-04-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多