问题
I am a newbie to the Spring boot (but worked in Laravel). I am facing a problem of cyclic redundancy in @ManyToMany relation. Let's go through the scenario -
What response I ma getting (fetching user's list which has many to many relationships with roles) -
Following is the ER-diagram of associated tables to manage many to many relationship between users
and roles
table.
User entity class has following code -
@Entity
@Where(clause = "deleted_at IS NULL")
@SQLDelete(sql = "UPDATE users SET deleted_at = CURRENT_TIMESTAMP WHERE id = ?", check = ResultCheckStyle.COUNT)
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "users")
@JsonIgnoreProperties(
value = {"createdAt", "updatedAt", "deletedAt"}
)
public class User {
@Id
@Column(name = "id", updatable = false, nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "name", nullable = false)
@NotBlank(message = "Name field can not be empty")
private String name;
.....
.....
.....
@ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER)
@JoinTable(name = "user_roles",joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
}
And Role entity is as follows -
@Entity
@Table(name = "roles")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@SQLDelete(sql = "UPDATE roles SET deleted_at = CURRENT_TIMESTAMP WHERE id = ?", check = ResultCheckStyle.COUNT)
@Where(clause = "deleted_at IS NULL")
@JsonIgnoreProperties(
value = {"createdAt", "updatedAt", "deletedAt"}
)
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private long id;
@Column(name = "title")
@NotBlank(message = "Title field must be not null")
private String title;
......
......
......
@OneToMany(targetEntity = User.class, fetch = FetchType.EAGER)
@JoinTable(name = "user_roles",joinColumns = @JoinColumn(name = "role_id"),
inverseJoinColumns = @JoinColumn(name = "user_id"))
private List<User> users;
}
How to solve this problem? What I am doing wrong here?
回答1:
Since you are fetching the list directly. You will have to mention the annotation @JsonIgnore
everywhere you have mapping specified. By everywhere I don't mean literally everywhere. Just use the annotation and see how it works.
Edit -> Just do it in roles table where you have mapped it to the user table. It will then skip the user mapping while fetching the data.
@JsonIgnore
private List<User> users;
回答2:
Easiest would probably be to annotate the List<T>
's with a @JsonIgnoreProperties
annotation to break the cyclic dependencies.
@JsonIgnoreProperties("users")
private List<Role> roles;
@JsonIgnoreProperties("roles")
private List<User> users;
回答3:
You could annotate users
within Role
with @JsonBackReference
.
来源:https://stackoverflow.com/questions/60151132/how-to-get-rid-of-cyclic-redundancy-while-having-manytomany-relation-jpa-spring