使用spring-data-jpa时,出现级联查询递归查询

/ 后端 / 没有评论 / 461浏览

很简答的三个表:

z_user(id,name,age),z_role(id,name),z_role_user(id,user_id,role_id);

其中z_role_user是关联表,user和role的关系是多对多,所以用到了@ManyToMany注解;

下面是三个实体:

@Entity
@Table(name = "z_user")
public class UserX {
    @Id()
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @Column(length = 10)
    private String name;
    @Column(length = 10)
    private Integer age;
    @JsonIgnoreProperties(value = {"users"})
    @ManyToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
    @JoinTable(name = "z_role_user",
            inverseJoinColumns = @JoinColumn(name = "role_id"),
            joinColumns = @JoinColumn(name = "user_id"))
    private List<RoleX> roles;

@Entity @Table(name = "z_role") public class RoleX { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; @JsonIgnoreProperties(value = {"roles"}) @ManyToMany(cascade = CascadeType.REFRESH, mappedBy = "roles") private List<UserX> users;

@Entity @Table(name = "z_role_user") public class RoleUser { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "user_id") private Integer userId; @Column(name = "role_id") private Integer roleId;

(1)解决方式就是使用 @JsonIgnoreProperties;对标注的字段,禁用对方实体的序列化,比如UserX对象,查出roles后,就禁止RoleX对象继续序列化继续递归查询用户信息了;

(2)其中还有个问题,就是如果关联表字段不写@Column中的name下划线方式,会重复的关联字段错误;比如userId,他会认为有userId和user_id两个字段;