如何将@Query(nativeQuery = true)结果导入List <myobject>?

时间:2018-01-18 18:24:38

标签: sql spring spring-data-jpa

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

3 个答案:

答案 0 :(得分:0)

也许这会对你有所帮助:

public interface ObjRepository extends JpaRepository<MyObject, Long> {

        @Query(value = "FROM MyObject WHERE objname = ?1")
        public List<MyObject> findByName(String name); 
    }

答案 1 :(得分:0)

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

使用本机查询时,我们得到Object数组的列表,即list中的每一行都是数组。数组中的元素表示列值。 在repo界面:

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;

在来电者中

{{1}}

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

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

答案 2 :(得分:0)

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