我正在寻找一种将一些 JPA 实体导出到 REST API 的方法,但不是每次我想根据入口点共享一些特定字段时都发送整个实体。这是一个小例子:
假设我们有一个Author
具有很少字段的类:
@Entity
public class Author implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = SEQUENCE)
private Long id;
@NotNull
@Size(min = 1, message = "{required.field}")
private String name;
@NotNull
@Size(min = 1, message = "{required.field}")
private String country;
private LocalDate birthDate;
// getters and setters
}
假设我们有这个 REST 服务(只有两种方法):
@Path("authors")
public class AuthorREST {
@Inject
private AuthorBC bc;
@GET
@Produces("application/json")
public List<Author> find(@QueryParam("q") String query) throws Exception {
List<Author> result;
if (Strings.isEmpty(query)) {
result = bc.findAll();
} else {
result = bc.find(query);
}
return result;
}
@GET
@Path("{id}")
@Produces("application/json")
public Author load(@PathParam("id") Long id) throws Exception {
Author result = bc.load(id);
if (result == null) {
throw new NotFoundException();
}
return result;
}
}
现在,这样,当我的 API 被调用时,我将始终拥有 4 个字段。
我知道如果我使用杰克逊我可以设置@JsonIgnore
到我想忽略的字段,它们将永远被忽略。
但是,如果我希望在某些情况下,我的整个实体由一个服务返回,而在其他服务(或同一服务中的其他方法)中,仅返回 2 或 3 个字段,该怎么办?
有办法做到吗?
@JsonView 和混合
您已经知道可以使用注释,例如@JsonIgnore https://fasterxml.github.io/jackson-annotations/javadoc/2.7/com/fasterxml/jackson/annotation/JsonIgnore.html and @JsonIgnoreProperties https://fasterxml.github.io/jackson-annotations/javadoc/2.7/com/fasterxml/jackson/annotation/JsonIgnoreProperties.html让杰克逊忽略一些属性。
您还可以检查@JsonView https://fasterxml.github.io/jackson-annotations/javadoc/2.7/com/fasterxml/jackson/annotation/JsonView.html注解。有关如何使用的一些详细信息@JsonView https://fasterxml.github.io/jackson-annotations/javadoc/2.7/com/fasterxml/jackson/annotation/JsonView.html使用 JAX-RS,看看here https://github.com/FasterXML/jackson-jaxrs-providers/issues/57.
如果修改 JPA 实体不是一个选项,请考虑混合注释,如此处所述answer https://stackoverflow.com/a/39790836/1426227.
数据传输对象
Data Transfer Object https://en.wikipedia.org/wiki/Data_transfer_object(DTO) 是一种具有明确定义目的的模式:将数据传输到远程接口, 就像网页服务。这种模式非常适合 REST API,并且使用 DTO,您将拥有更多灵活性从长远来看。一旦 REST 资源表示不需要具有与持久性对象相同的属性,您就可以根据需要定制类。
为了避免样板代码,您可以使用映射框架,例如映射结构 http://mapstruct.org/将 REST API DTO 映射到持久性对象。
有关使用 DTO 的好处的详细信息,请查看以下答案:
- 为什么应该在 REST API 中使用 DTO https://stackoverflow.com/a/36175349/1426227
- 使用定制的请求和响应类别 https://stackoverflow.com/a/37387553/1426227
要为您的 DTO 提供更好的名称,请检查以下答案:
- 为您的 DTO 指定有意义的名称 https://stackoverflow.com/a/35341664/1426227
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)