Exception:org.hibernate.AnnotationException: mappedBy reference an unknown target entity property

Exception:org.hibernate.AnnotationException: mappedBy reference an unknown target entity property

This exception is thrown when Hibernate cannot find the property specified in the mappedBy attribute on the target entity. For instance, if you have a @OneToMany relationship in EntityA mapped by EntityB, but EntityB does not have the specified property, Hibernate will throw this exception. Let’s understand with an example, Suppose you have two entities, Author and Books, with a one-to-many relationship. The Author entity should reference a list of Books, and each Books should reference its parent Author.

Incorrect Code Example: Here is an incorrect example that will cause AnotationException.

@Entity
public class Author{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // Other fields...

    @OneToMany(mappedBy = "authorId", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Books> books= new ArrayList<>();

    // Getters and setters...
}
@Entity
public class Books{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "author_id")
    private Author author;

    // Other fields...

    // Getters and setters...
}

In the Author entity, the @OneToMany annotation references a non-existent property authorId in the Books entity. The correct property name is Author.

Correct Code Example: To fix this, make sure the mappedBy attribute references the correct property in the Books entity.

@Entity
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // Other fields...

    @OneToMany(mappedBy = "Author", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Books> books = new ArrayList<>();

    // Getters and setters...
}
@Entity
public class Books{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "author_id")
    private Author author;

    // Other fields...

    // Getters and setters...
}
  • Consistency in Property Names: Ensure that the property names used in the mappedBy attribute are consistent with the property names defined in the target entity.
  • Verify Annotations: Double-check all your annotations to make sure they correctly reference the relationships between entities.

By ensuring that the mappedBy attribute references the correct property, you can avoid the AnnotationException and properly establish the relationship between your entities.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *