Question
What does the error 'org.hibernate.AnnotationException: @OneToOne or @ManyToOne on entities.Ques#tion.examId references an unknown entity: long' mean and how can it be resolved?
// Example of a possible entity definitions
@Entity
public class Question {
@Id
private Long id;
@OneToOne
@JoinColumn(name = "exam_id")
private Exam exam;
}
@Entity
public class Exam {
@Id
private Long id;
}
Answer
The 'org.hibernate.AnnotationException' indicates that Hibernate is unable to map the relationship in the entity class due to an unknown entity reference. This can occur when the data type of the referenced entity is not properly annotated as an entity or is mismatched with the expected type.
// Correct the entity class above
@Entity
public class Question {
@Id
private Long id;
@OneToOne
@JoinColumn(name = "exam_id")
private Exam exam;
}
@Entity
public class Exam {
@Id
public Long id;
}
Causes
- The field referencing another entity is not properly annotated with @Entity.
- The type of the referenced field does not correspond to an actual entity class.
- Improper import statements might lead to confusion in class references.
Solutions
- Ensure that the class referenced by @OneToOne or @ManyToOne is properly annotated with @Entity.
- Verify that the referenced field's type is indeed an entity, not a primitive or non-entity type.
- Check the import statements in your Java class to ensure you are referencing the correct classes.
Common Mistakes
Mistake: Annotating a primitive type instead of an entity reference.
Solution: Ensure that the reference field is an object of a class that is marked as an entity.
Mistake: Forgetting to declare the associated entity with @Entity annotation.
Solution: Confirm that the referenced entity class is correctly defined and annotated.
Helpers
- Hibernate AnnotationException
- Hibernate entity mapping
- @OneToOne relation in Hibernate
- unknown entity in Hibernate
- Hibernate troubleshooting