如何在拥有@ManyToMany关系JPA springboot时摆脱循环冗余 [英] How to get rid of cyclic redundancy while having @ManyToMany relation JPA springboot

查看:516
本文介绍了如何在拥有@ManyToMany关系JPA springboot时摆脱循环冗余的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring靴的新手(但曾在Laravel工作).我在@ManyToMany关系中面临循环冗余的问题.让我们看一下场景-

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) -

以下是关联表的ER图,用于管理usersroles表之间的多对多关系.

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;

}

角色实体如下-

@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?

推荐答案

您可以在Role中用@JsonBackReference注释users.

这篇关于如何在拥有@ManyToMany关系JPA springboot时摆脱循环冗余的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆