gpt4 book ai didi

java - Hibernate 继承 - OneToMany 与 2 类扩展父不起作用

转载 作者:行者123 更新时间:2023-11-29 04:08:28 25 4
gpt4 key购买 nike

我有 3 个实体:

@Data
@AllArgsConstructor
@Entity
@Table(name = "beneficiary")
@Inheritance
@DiscriminatorColumn(discriminatorType = DiscriminatorType.STRING, name = "type")
public abstract class Beneficiary {
public Beneficiary() {}

@Id private String id;

private String description;
}


@Data
@Entity
@DiscriminatorValue("company")
@EqualsAndHashCode(callSuper = true)
public class BeneficiaryCompany extends Beneficiary {
public BeneficiaryCompany() {
super();
}

public BeneficiaryCompany(String id, String description) {
super(id, description);
}
}


@Data
@Entity
@DiscriminatorValue("person")
@EqualsAndHashCode(callSuper = true)
public class BeneficiaryPerson extends Beneficiary {
public BeneficiaryPerson() {}

public BeneficiaryPerson(String id, String description) {
super(id, description);
}
}

在另一个类中,我想要 2 个独立的集合:

@Data
@AllArgsConstructor
@Entity
@Table(name = "transaction")
public class Transaction {

public Transaction() {}

@Id private String id;

private String description;

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, targetEntity = BeneficiaryCompany.class)
@JoinColumn(name = "transaction_id", nullable = false)
private Set<BeneficiaryCompany> beneficiaryCompanies;

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true,targetEntity = BeneficiaryPerson.class)
@JoinColumn(name = "transaction_id", nullable = false)
private Set<BeneficiaryPerson> beneficiaryPeople;
}

问题是每个 Beneficiary 都被提取到 beneficiaryCompanies 中,而 beneficiaryPeople 在调试器中告诉我:

Unable to evaluate the expression Method threw 'org.hibernate.WrongClassException' exception.

数据库记录看起来不错(已创建 DiscriminatorColumn)。可能是什么问题呢?为什么 beneficiaryCompanies 包含 BeneficiaryPerson 对象?

@编辑:为了获取记录,我使用了 SpringData JPA 存储库。

最佳答案

Use @MappedSuperclass on your base class Beneficiary

Alexandar Petrov 完全正确。您必须删除 @Entity 因为父类(super class)不是实体。在处理扩展类的继承时,您可以在基类上使用 @MappedSuperclass 注释,在您的情况下,它是 Beneficiary

编辑: This是一篇很好的文章,您可以引用。

关于java - Hibernate 继承 - OneToMany 与 2 类扩展父不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56666670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com