【发布时间】:2015-11-20 16:39:41
【问题描述】:
我有一个看起来像这样的控制器
@RestController
public class LocationsController {
@Autowired
private EntityManager manager;
private String withinQuery =
"WITH L as\n" +
"\n" +
"(SELECT *\n" +
"FROM location\n" +
"\n" +
"WHERE ST_Distance(ST_FlipCoordinates(location.shape), ST_FlipCoordinates(ST_GeomFromGeoJSON('%s'\n" +
" )))=0)\n" +
"\n" +
"SELECT *\n" +
"FROM L\n" +
"WHERE id NOT IN (\n" +
"SELECT metalocation_id FROM location\n" +
"WHERE metalocation_id IS NOT NULL\n" +
")";
private String nearestQuery =
"select * from location order by ST_Distance(ST_FlipCoordinates(location.shape), ST_FlipCoordinates(St_GeomFromGeoJSON('%s'))) limit 1";
@RequestMapping(value="near", method = RequestMethod.GET)
public List<Location> getNearestLocations(@RequestParam(value = "point") String pointAsString) throws IOException {
List<Location> locationCloseToPoint = manager.createNativeQuery(String.format(withinQuery, pointAsString), Location.class).getResultList();
if (locationCloseToPoint.size() == 0) {
List<Location> closesLocation = manager.createNativeQuery(String.format(nearestQuery, pointAsString), Location.class)
.getResultList();
locationCloseToPoint.addAll(closesLocation);
}
return locationCloseToPoint;
}
}
如您所见,它返回位置列表。
@Entity
public class Location {
public Geometry getShape() {
return shape;
}
public void setShape(Geometry shape) {
this.shape = shape;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
private Geometry shape;
@ManyToOne(cascade = CascadeType.ALL)
private Location metalocation;
问题是我想以 spring data rest 用于位置资源的格式返回此列表,其中包含所有 hateoas 字段和内容。更具体地说,我想在输出中有一个指向元定位的链接。
我读过关于 spring-hateoas 和 ResourceAssembler 和 @RepositoryRestController 的内容,我认为我可以通过编写自定义 ResourceAssembler 来复制 spring-data-rest 正在做的事情,但我不想这样做,因为你知道,我为什么要想写spring-data-rest已经写好的代码吧?
他们自动完成所有这些组装工作,对吧?因为我在 http 输出中看到了它。所以我觉得应该有办法使用它。
【问题讨论】:
标签: spring rest spring-data-rest spring-hateoas