【问题标题】:JPA serialize enttiyJPA 序列化实体
【发布时间】:2023-03-30 09:26:01
【问题描述】:

我的数据模型包含 3 个表:User、Profile、UserProfile。

public class User implements Serializable {

 private Integer id;
 ......

 @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = 
 FetchType.LAZY)
 @JsonManagedReference
 @JsonProperty("profiles")
 private List<UserProfile> userProfiles = new ArrayList<UserProfile>();

}

public class Profile implements Serializable {
 private Integer id;
 ......

 @OneToMany(mappedBy="profile", cascade = CascadeType.ALL,  fetch = 
 FetchType.LAZY)
 @JsonBackReference
 private List<UserProfile> userProfiles= new ArrayList<UserProfile>();

}

public class UserProfile implements Serializable {
 private Integer id;

 @ManyToOne
 @JoinColumn(name = "idUser")
 @JsonBackReference
 private User user;

 @ManyToOne
 @JoinColumn(name = "idProfile")
 @JsonManagedReference
 private Profile profile;
}

这是我的 json 反馈:

{ “身份证”:1, ………… “个人资料”:[ { “轮廓”: { “身份证”:1, ...... }, { “身份证”:2, ...... } } ] }

我有两个问题: 是否可以删除配置文件属性并具有: { “身份证”:1, ………… “个人资料”:[ { “身份证”:1, ...... }, { ": 2, ...... } ] }

在与包含主键(id)的中间表的多对多关系中,2个外键是具有多对多关系的2个表的id,这是怎么做的?

【问题讨论】:

    标签: json jpa serialization spring-data-jpa spring-data


    【解决方案1】:

    对于第一个问题,隐藏profile属性,有2个选项: 1.如果在任何json输出中都不需要它,可以给它加上@JsonIgnore注解; 2. 如果你在其他地方需要它,但在这里不想要它,你可以使用Projection。查看https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projectionshttps://www.baeldung.com/spring-data-rest-projections-excerpts 以获取有关如何使用投影的参考。

    【讨论】:

    • 我想知道这是否可以实现,因为当我想进行更新时,我无法思考,因为我不会拥有我的所有 ID。当我要对用户进行更新时,它还必须更新 UserProfile 表中的信息。
    • 请帮帮我。这很重要
    【解决方案2】:

    再次检查您的代码。你的代码有问题。 您只需要 2 个实体:UserProfile。只需添加@ManyToMany 关系即可。 有关ManyToMany https://vladmihalcea.com/the-best-way-to-use-the-manytomany-annotation-with-jpa-and-hibernate/ 的完整示例,请参阅此处

    【讨论】:

    • 我需要 UserProfile 链接实体,因为之后我会在其中添加其他字段
    • 帮帮我。很紧急
    猜你喜欢
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多