[英]What is the best way to get response without HATEOAS?
I tried get entity by Data JPA & Data Rest without HATEOAS. 我尝试通过Data JPA和Data Rest获取实体而不使用HATEOAS。
The condition is that I use the HATEOAS form, and sometimes I need a pure Json response. 条件是我使用HATEOAS表单,有时我需要一个纯Json响应。
So I'm creating JSON by creating the controller path separately from the repository's endpoint and creating the DTO class separately. 所以我通过分别从存储库的端点创建控制器路径并分别创建DTO类来创建JSON。
this is my code : 这是我的代码:
@RepositoryRestController
public class MetricController {
@Autowired
private MetricRepository metricRepository;
@RequestMapping(method = RequestMethod.GET, value = "/metrics/in/{id}")
public @ResponseBody
MetricDTO getMetric(@PathVariable Long id) {
return MetricDTO.fromEntity(metricRepository.getOne(id));
}
}
@RepositoryRestResource
public interface MetricRepository extends JpaRepository<Metric, Long> { }
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class MetricDTO {
private SourceType sourceType;
private String metricTypeField;
private String metricType;
private String instanceType;
private String instanceTypeField;
private List<String> metricIdFields;
private List<String> valueFields;
private Map<String, String> virtualFieldValueEx;
public static MetricDTO fromEntity(Metric metric) {
return new MetricDTO(
metric.getSourceType(),
metric.getMetricTypeField(),
metric.getMetricType(),
metric.getInstanceType(),
metric.getInstanceTypeField(),
metric.getMetricIdFields(),
metric.getValueFields(),
metric.getVirtualFieldValueEx()
);
}
}
It's the way I do, but I expect there will be better options and patterns. 这就是我的方式,但我希望会有更好的选择和模式。
The question is, I wonder if this is the best way. 问题是,我想知道这是不是最好的方法。
HATEOAS (Hypermedia as the Engine of Application State) is a constraint of the REST application architecture. HATEOAS (超媒体作为应用程序状态的引擎)是REST应用程序体系结构的约束。 It basically tells that anyone who is a consumer of your REST endpoints can navigate between them with the help of the link. 它基本上告诉任何作为REST端点的消费者的人可以在链接的帮助下在它们之间导航。
let take your example 让我们举个例子
**HTTP Method** **Relation (rel)** **Link**
GET Up /metrics/in
GET Self /metrics/in/{id}
GET SourceType /sourceType/{id}
GET metricIdFields /url for each in JSON aarray
Delete Delete /employe/{employeId}
Use org.springframework.hateoas.Links
class to create such link in your DTOs. 使用org.springframework.hateoas.Links
类在您的DTO中创建此类链接。
in you DTO add 在你DTO添加
public class MetricDTO {
private Links links;
//Getters and setters
//inside your setters add SLEF , GET , create Delete for current resource
}
https://www.baeldung.com/spring-hateoas-tutorial https://www.baeldung.com/spring-hateoas-tutorial
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.