【发布时间】:2018-06-27 22:02:48
【问题描述】:
您好,我有一个查询,我希望将结果放入对象列表中,而不是实体。但结果实际上是一个我应该转移到我的对象的对象。有没有办法将它直接映射到我的自定义对象?
【问题讨论】:
标签: sql spring spring-data-jpa
您好,我有一个查询,我希望将结果放入对象列表中,而不是实体。但结果实际上是一个我应该转移到我的对象的对象。有没有办法将它直接映射到我的自定义对象?
【问题讨论】:
标签: sql spring spring-data-jpa
也许这会对你有所帮助:
public interface ObjRepository extends JpaRepository<MyObject, Long> {
@Query(value = "FROM MyObject WHERE objname = ?1")
public List<MyObject> findByName(String name);
}
【讨论】:
方法一:使用对象数组列表。
当使用原生查询时,我们得到对象数组的列表,即列表中的每一行都是数组。数组中的元素表示列值。 在 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。
【讨论】:
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()));
}
【讨论】: