【问题标题】:JPA and Lombok causing StackOverflowError in circular dependencyJPA 和 Lombok 在循环依赖中导致 StackOverflowError
【发布时间】:2021-02-02 12:21:20
【问题描述】:

我有两个实体类:

@Data
@Entity(name = "user")
@Table(name = "tbl_user")
@EqualsAndHashCode(callSuper = true, exclude = "products")
public class UserEntity extends BaseEntity {

    @Column(unique = true)
    private String username;

    @ToString.Exclude
    private String password;

    @Transient
    @JsonProperty("remember_me")
    private Boolean rememberMe;

    @Enumerated(EnumType.STRING)
    @CollectionTable(name = "tbl_user_role")
    @ElementCollection(fetch = FetchType.EAGER)
    Set<Role> roles = new HashSet<>();

    @OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private List<ProductEntity> products = new ArrayList<>();
}
@Data
@Entity
@Table(name = "tbl_product")
@EqualsAndHashCode(callSuper = true)
public class ProductEntity extends BaseEntity {

    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false)
    private UserEntity user;
    private String productName;
}

都扩展了 baseEntity:

@MappedSuperclass
public abstract class BaseEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Version
    private long version;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        BaseEntity that = (BaseEntity) o;
        return Objects.equals(id, that.id) && Objects.equals(version, that.version);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, version);
    }
}

现在,当我尝试检索所有产品(或所有用户)(例如 findAll 方法)时,我得到一个 StackOverflowError。 我知道这个错误是由用户和产品之间的循环依赖引起的,所以我在 userEntity 中的 equals 注释中添加了一个排除来解决它,如下所示:

@EqualsAndHashCode(callSuper = true, exclude = "products")

不幸的是,错误不断弹出。我在这里错过了什么?

【问题讨论】:

  • 请注意,一般来说,为实体覆盖 equals 和 hashCode 并不是一个好主意。将实体与值区分开来的具体特征是实体具有独立于其数据的身份。

标签: java spring-boot jpa lombok circular-dependency


【解决方案1】:

我设法通过将@ToString.Exclude 添加到roles 和user 类变量来解决此问题。显然我在代码后面的某个地方打印了它们,这导致了错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 2021-09-27
    • 2015-06-08
    • 2018-07-22
    • 2023-03-13
    • 2013-03-18
    相关资源
    最近更新 更多