Hibernate inheritance – Reference entity using @mappedsuperclass comment

@MappedSuperclass
public abstract class AbstractBaseModel{ }

@MappedSuperclass
public class Person extends AbstractBaseModel {}

@Entity
public class APerson extends Person {}

@Entity
public class BPerson extends Person {}

@Entity< br />public class Course extends AbstractBaseModel {
@ManyToOne
@JoinColumn(name ="person")
private Person person;
}

The above structure An exception will be given:

Caused by: org.hibernate.AnnotationException: @OneToOne or @ManyToOne on 
Course references an unknown entity: Person

It means that you cannot use Person in the mapping because it is not a specific entity. How can I implement such an inheritance scheme?

Very simple, you change the @MappedSuperclass annotation on Person to @Entity

Use @MappedSuperclass only if you clearly don’t want the class to be queryable or part of the relationship. @Entity is everywhere.

A good heuristic decision is up to you Is the superclass abstract-if it is-use @MappedSuperclass, just like you did on AbstractBaseModel

@MappedSuperclass
public abstract class AbstractBaseModel{ }

@MappedSuperclass
public class Person extends AbstractBaseModel {}

@Entity
public class APerson extends Person {}
< br />@Entity
public class BPerson extends Person {}

@Entity
public class Course extends AbstractBaseModel {
@ManyToOne
@JoinColumn(name ="person")
private Person person;
}

The above structure will give an exception:

Caused by: org.hibernate.AnnotationException: @OneToOne or @ManyToOne on 
Course references an unknown entity: Person

It means that you cannot use Person in the mapping because it is not a specific entity. How do I To implement such an inheritance scheme?

It’s very simple, you change the @MappedSuperclass annotation on Person to @Entity

Only if you clearly do not want the Use @MappedSuperclass when the class is queryable or part of a relationship. @Entity is everywhere.

A good heuristic decision is to see if your superclass is abstract-if it is-use @ MappedSuperclass, just like you do on AbstractBaseModel

Leave a Comment

Your email address will not be published.