问题
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.
回答1:
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.
回答2:
How about the Student class. Have you defined ManyToOne relationship in the Student class.
@Entity
public class Student {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
@ManyToOne
private Department department;
..................
Please check this example.
来源:https://stackoverflow.com/questions/28710346/annotationexception-referenced-property-not-a-onemanytoone