简体   繁体   English

Java Spring boot JPA循环引用

[英]Java Spring boot JPA circular referencing

using MySQL, Java, Spring Boot and JPA使用 MySQL、Java、Spring Boot 和 JPA

I have two objects, user and module.我有两个对象,用户和模块。

A user can have many modules and a module can have many users.一个用户可以有很多模块,一个模块可以有很多用户。

A module is structured the following way:一个模块的结构如下:

@Entity
@Table(name = "module")
public class Module {
    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @ManyToMany
    @JoinTable(name="module_users",
       joinColumns = @JoinColumn(name="module_id"),
       inverseJoinColumns =  @JoinColumn(name = "user_id")
    )
    private Set<User> users = new HashSet<>();

A user is structured the following way:用户的结构如下:

@Entity
@Table(name = "user")
public class User implements Serializable {
    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY) 
    public Long id;
    public String name;
    private String email;
    @JsonIgnore
    @ManyToMany(mappedBy = "users")
    public Set<Module> modules = new HashSet<>();

Having @JsonIgnore annotation does "work" when calling modules, but I also need to call a user and its modules ideally.调用模块时,@JsonIgnore 注释确实“起作用”,但我还需要理想地调用用户及其模块。 Any suggestions to support both of these without crashing from circular referencing?有什么建议可以支持这两种方法而不会因循环引用而崩溃?

在这种情况下你可以使用 DTO 检查这里

Use these two annotations @JsonManagedReference and @JsonBackReference使用这两个注解@JsonManagedReference 和@JsonBackReference

Ref: http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion参考: http ://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion

@Entity
@Table(name = "module")
public class Module {
    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @ManyToMany
    @JoinTable(name="module_users",
       joinColumns = @JoinColumn(name="module_id"),
       inverseJoinColumns =  @JoinColumn(name = "user_id")
    )
    @JsonBackReference
    private Set<User> users = new HashSet<>();

A user is structured the following way:

@Entity
@Table(name = "user")
public class User implements Serializable {
    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY) 
    public Long id;
    public String name;
    private String email;
    @JsonManagedReference
    @ManyToMany(mappedBy = "users")
    public Set<Module> modules = new HashSet<>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM