JPA。 Stackoverflow 上的级联合并
JPA. Stackoverflow on cascade merge
这是我的 JPA 结构:
电影(看级联类型):
@Entity
@Table(name = "movie")
public class Movie {
@Id
@Column(name = "movie_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
//@OneToMany(cascade = CascadeType.ALL, mappedBy = "primaryKey.movie") //stack overflow
@OneToMany(mappedBy = "primaryKey.movie") //works fine
private List<Rating> ratings;
....
}
评分:
@Entity
@Table(name = "rating")
@AssociationOverrides({@AssociationOverride(name = "primaryKey.movie", joinColumns = @JoinColumn(name = "movie_id")),
@AssociationOverride(name = "primaryKey.user", joinColumns = @JoinColumn(name = "imdb_user_id"))})
public class Rating {
@EmbeddedId
private RatingId primaryKey = new RatingId();
@Column(name = "rating_value")
private Integer ratingValue;
.....
}
评级编号:
@Embeddable
public class RatingId implements Serializable{
@ManyToOne
private Movie movie;
@ManyToOne
private User user;
}
当我用 CascadeType.ALL
调用 entityManager.merge(Movie movie)
时,我得到了 WhosebugError。如果删除级联,合并调用不会抛出错误。哪里可能有问题?
我认为这个问题与复合主键有关。 merge
对具有相同一对多关系但没有复合 id 的另一个实体执行时没有错误。
Whosebug 是由循环关系引起的。为了避免异常,我将多对多 table 中的键标记为 @ManyToOne(fetch = FetchType.LAZY)
.
这就是我的 table 修改后的样子:
这是我的 JPA 结构:
电影(看级联类型):
@Entity
@Table(name = "movie")
public class Movie {
@Id
@Column(name = "movie_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
//@OneToMany(cascade = CascadeType.ALL, mappedBy = "primaryKey.movie") //stack overflow
@OneToMany(mappedBy = "primaryKey.movie") //works fine
private List<Rating> ratings;
....
}
评分:
@Entity
@Table(name = "rating")
@AssociationOverrides({@AssociationOverride(name = "primaryKey.movie", joinColumns = @JoinColumn(name = "movie_id")),
@AssociationOverride(name = "primaryKey.user", joinColumns = @JoinColumn(name = "imdb_user_id"))})
public class Rating {
@EmbeddedId
private RatingId primaryKey = new RatingId();
@Column(name = "rating_value")
private Integer ratingValue;
.....
}
评级编号:
@Embeddable
public class RatingId implements Serializable{
@ManyToOne
private Movie movie;
@ManyToOne
private User user;
}
当我用 CascadeType.ALL
调用 entityManager.merge(Movie movie)
时,我得到了 WhosebugError。如果删除级联,合并调用不会抛出错误。哪里可能有问题?
我认为这个问题与复合主键有关。 merge
对具有相同一对多关系但没有复合 id 的另一个实体执行时没有错误。
Whosebug 是由循环关系引起的。为了避免异常,我将多对多 table 中的键标记为 @ManyToOne(fetch = FetchType.LAZY)
.
这就是我的 table 修改后的样子: