【发布时间】: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