我有一个问题,好几天都无法解决。我读了很多文档,搜索了很多论坛,但没有找到解决方案。 我继承了类,代码如下所示:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "nc_linktype", discriminatorType = DiscriminatorType.STRING)
@Table(name = "mk_newsletter_coupons")
@DiscriminatorOptions(force = true)
public class BaseNewsletterCoupon extends BaseEntity {...}
@Entity
@DiscriminatorValue("expire")
public class NewsletterCouponsExpire extends BaseNewsletterCoupon {
@Entity
@DiscriminatorValue("region")
public class NewsletterCouponsRegion extends BaseNewsletterCoupon {
我想在 OneToMany 现实的多方面使用这些特定实体:
@Entity(name = "newsletter")
@Table(name = "mk_newsletters")
@Configurable
public class NewsLetter extends BasePictureEntity {
@OneToMany(mappedBy = "newsletter", cascade = { CascadeType.ALL }, orphanRemoval = true, fetch = FetchType.LAZY)
@IndexColumn(name = "nc_index")
@OrderColumn(name = "nc_index")
@OrderBy("index")
List<NewsletterCouponsExpire> expireCoupons = new ArrayList<NewsletterCouponsExpire>();
@OneToMany(mappedBy = "newsletter", cascade = { CascadeType.ALL }, orphanRemoval = true, fetch = FetchType.LAZY)
@IndexColumn(name = "nc_index")
@OrderColumn(name = "nc_index")
@OrderBy("index")
List<NewsletterCouponsRegion> regionCoupons = new ArrayList<NewsletterCouponsRegion>();
当我坚持这个时事通讯实体时,所有记录都会很好地创建。 如果我修改列表的内容,似乎 orphanRemoval = true 属性不起作用,因为旧记录保留在表中,并且创建了新记录。 如果我从基本实体中删除 @DiscriminatorOptions 注释,旧记录将被删除,但继承鉴别器不再工作,因此 JPA 提供程序(hibernate)尝试将每个子记录加载到每个集合中,这会导致一个组织.hibernate.loader.Loader.instanceAlreadyLoaded 异常。
有人成功实现了这样的模型,或者知道这个问题的任何解决方法吗?
您可以尝试使用 Hibernate 原生的 @Cascade 注解进行级联删除孤儿,而不是 JPA 的孤儿删除。 有机会它可能会起作用。
让我知道它是否对您有用。
今天我在这篇文章中遇到了类似的问题。
我的场景是
以@Inheritance策略加入的父实体类。 该父类有一个 OneToMany Set 子级,其级联 All 和孤儿移除为 true。
子类使用公共 id 扩展父类以进行歧视加入
目标是毫无问题地干净地保存子类实体。
好吧,断言失败了,错误是 hibernate orphanremoval null 等等。
在对 junit 进行各种测试之后,我意识到只有当父类上的子级列表必须用空列表初始化时,保存才有效。