Spring Boot @ManyToOne only Id @JsonProperty [英] Spring Boot @ManyToOne only Id @JsonProperty
问题描述
帮我找到 JSON 属性注释,谁让我选择一个实体属性来进行 JSON 序列化.我只需要一个.
help me find JSON property annotation who give me choose an entity property to JSON serialization. I need only one.
我是这样编码的:
@Entity
@Table(name = "pages")
public class Page {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@JsonIgnoreProperties(value = {"name", "description", "pages"}) // it's working, but I want to simplify, I need only project id property to JSON
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "project_id")
private Project project;
//getters and setters
}
和项目实体:
@Entity
@Table(name = "projects")
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "project_id")
private Long id;
@Column(name = "project_name")
private String name;
@Column(name = "description")
private String description;
@OneToMany(targetEntity = Page.class, mappedBy = "project", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@OrderBy("id")
private List<Page> pages = new ArrayList<>();
}
JSON 应该是:
{
"id": 10,
"name": "Name",
"project": {"id":1}
}
推荐答案
您应该创建一个 DataTransferObject (DTO),而不是使用过多的注释.
Instead of working with too many annotations you should create a DataTransferObject (DTO) instead.
在 DTO 中,您可以准确定义应该公开哪些信息,并将每个实体对象映射到 DTO.这将返回到前端,而不是实体本身.
Within the DTO you define exactly what information should be exposed and map every entity object to a DTO. This is than returned to the frontend, not the entity itself.
这是关于该主题的一个很好的教程:https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application
Here is a good tutorial on the topic: https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application
这篇关于Spring Boot @ManyToOne only Id @JsonProperty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!