我有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;
}
问题是每个受益人都被拿到了受益公司,而调试器中的受益人告诉我:
无法评估表达式方法抛出 “ org.hibernate.WrongClassException”异常。
数据库记录看起来不错(已创建DiscriminatorColumn)。可能是什么问题呢?为什么beneficiaryCompany包含BeneficiaryPerson对象?
@EDIT: 为了获取记录,我使用的是SpringData JPA存储库。
答案 0 :(得分:2)
在基础类
@MappedSuperclass
上使用Beneficiary
亚历山大·彼得罗夫(Alexandar Petrov)绝对正确。您必须删除@Entity
,因为超类不是实体。在处理继承扩展类时,可以在基类上使用@MappedSuperclass
注释,在您的情况下为Beneficiary
。
编辑: This是非常好的文章,您可以参考。