我有一个班级
@Entity
@Table(name = "movies")
@Data
public class MovieEntity implements Serializable {
...
@OneToMany(mappedBy = "movie", cascade = CascadeType.ALL)
private Set<MovieRate> ratings;
}
映射列表
@Entity
@Table(name = "movies_ratings")
@Data
public class MovieRate {
...
}
加载movie.getRatings()
时,列表会将我抛出
...
at org.eclipse.persistence.indirection.IndirectSet.buildDelegate(IndirectSet.java:225) ~[org.eclipse.persistence.core-2.7.0.jar:na]
at org.eclipse.persistence.indirection.IndirectSet.getDelegate(IndirectSet.java:436) ~[org.eclipse.persistence.core-2.7.0.jar:na]
at org.eclipse.persistence.indirection.IndirectSet.hashCode(IndirectSet.java:485) ~[org.eclipse.persistence.core-2.7.0.jar:na]
at com.core.jpa.entity.MovieEntity.hashCode(MovieEntity.java:21) ~[classes/:na]
at com.core.jpa.entity.movie.MovieRate.hashCode(MovieRate.java:16) ~[classes/:na]
at java.util.HashMap.hash(HashMap.java:338) ~[na:1.8.0_144]
at java.util.HashMap.put(HashMap.java:611) ~[na:1.8.0_144]
at java.util.HashSet.add(HashSet.java:219) ~[na:1.8.0_144]
at org.eclipse.persistence.queries.ReadAllQuery.registerResultInUnitOfWork(ReadAllQuery.java:968) ~[org.eclipse.persistence.core-2.7.0.jar:na]
...
所有错误https://pastebin.com/RgNg84Cb
问题可能在于Lombok注释。但我不知道是什么。
答案 0 :(得分:2)
显然,异常是由Lombok生成的MovieRate.hashcode()
和MovieEntity.hascode()
引起的,以解决您在@EqualsAndHashCode
中添加MovieRate
的问题或者在MovieEntity
或两者中:
@Entity
@Table(name = "movies")
@Data @EqualsAndHashCode(exclude = "ratings")
public class MovieEntity implements Serializable {
// Your code
}
或
@Entity
@Table(name = "movies_ratings")
@Data @EqualsAndHashCode(exclude = "movie")
public class MovieRate {
...
}
为什么呢? @Data(因为它使用@EqualsAndHashCode)以生成hashCode()
:
默认情况下,它将使用所有非静态非瞬态字段
因此它也将使用MovieEntity.ratings
和MovieRate.movie
,并且每一方的hashCode()
方法调用将调用另一方的hashCode()
,因为它是双向的关联,它将无限运行直到java.lang.StackOverflowError
。
注意:对于两个实体,toString()
(也由@Data
}方法生成的方法都会出现相同的错误,因为每个实体都会尝试打印另一方。要解决此问题,您可以添加@ToString以排除相同的字段。