Hibernate继承-具有扩展父类的2类的OneToMany无法正常工作

时间:2019-06-19 11:29:54

标签: java hibernate spring-data

我有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存储库。

1 个答案:

答案 0 :(得分:2)

  

在基础类@MappedSuperclass上使用Beneficiary

亚历山大·彼得罗夫(Alexandar Petrov)绝对正确。您必须删除@Entity,因为超类不是实体。在处理继承扩展类时,可以在基类上使用@MappedSuperclass注释,在您的情况下为Beneficiary

编辑: This是非常好的文章,您可以参考。