Reputation: 1038
I have 3 Entities:
@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);
}
}
An in the other class I want to have 2 separate collections:
@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;
}
The problem is that every Beneficiary was fetched into beneficiaryCompanies, and beneficiaryPeople in the debugger tells me that:
Unable to evaluate the expression Method threw 'org.hibernate.WrongClassException' exception.
The database records looks fine (DiscriminatorColumn was created). What could be the problem? Why beneficiaryCompanies contains BeneficiaryPerson objects?
@EDIT: To fetch the records I am using SpringData JPA repositories.
Upvotes: 2
Views: 512
Reputation: 2532
Add @DiscriminatorOptions(force = true)
to Beneficiary
class. This will force Hibernate to use the discriminator when it fetches the collections.
Upvotes: 0
Reputation: 2571
Use
@MappedSuperclass
on your base classBeneficiary
Alexandar Petrov is absolutely correct. You have to remove @Entity
because superclass is not an entity. When dealing with inheritance extending a class, you can use @MappedSuperclass
annotation on the base class, in your case, it is Beneficiary
.
Edit: This is a very good article you can refer to.
Upvotes: 3