AnnotationException Referenced property not a (One|Many)ToOne

hibernate, jakarta-ee, java, spring

Solution

You have incorrectly set up your mapping. Hibernate is complaining that no field called `departmentId` is available to set up a one to one or many relationship, and it is correct.

You want to map your values like this.

Department.Java

@Entity
@Table(name="department", catalog="student")
public class Department {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer departmentId;

    @OneToOne
    @JoinColumn(name = "id")
    private DepartmentHead departmenthead;
}       

DepartmentHead.java

@Entity
@Table(name="departmenthead", catalog = "student")
public class DepartmentHead {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;

    @OneToOne(mappedBy = "departmenthead")
    private Department department;  
}

You point the `Department` field in `DepartmentHead` at the `DepartmentHead` field inside the `Department`. Hibernate sorts out what ID's to use, you don't have to specify that in the actual link.

Problem

I tried to make one-to-one relationship. But I get error: ``` AnnotationException Referenced property not a (One|Many)ToOne on com.student.information.service.Department.departmentId in mappedBy of com.student.information.service.DepartmentHead.department ``` Both the entities are almost identical. Department can exists with out department head. Department.Java ``` @Entity @Table(name="department", catalog="student") public class Department { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer departmentId; @Column(name="dept_name") private String departmentName; @OneToMany(mappedBy="department",cascade = CascadeType.ALL) private List<Student> student; @OneToOne(targetEntity=Department.class) private DepartmentHead departmenthead; } ``` DepartmentHead.java ``` @Entity @Table(name="departmenthead", catalog = "student") public class DepartmentHead { //This is mapped with the department id @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; @Column(name="headname") private String headName; @OneToOne(mappedBy = "departmentId",fetch = FetchType.LAZY,cascade=CascadeType.ALL) @JoinColumn(name="dept_id") private Department department; } ``` Caused by: org.hibernate.AnnotationException: Referenced property not a (One|Many)ToOne: can someone please point me in the right direction about what mistake am I making. I am struggling from past 2 days and not able to figure out the solution for the issue. Thanks in advance for help.

Original source

Related problems