AnnotationException引用的属性不是(一个|多个)ToOne

时间:2015-02-25 03:00:50

标签: java spring hibernate java-ee

我试图建立一对一的关系。但我得到错误:

AnnotationException Referenced property not a (One|Many)ToOne
on
com.student.information.service.Department.departmentId in mappedBy of com.student.information.service.DepartmentHead.department

两个实体几乎完全相同。部门可以存在部门主管。

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;  
}

引起:org.hibernate.AnnotationException:引用的属性不是(一个|多个)ToOne:

有人可以指出我正确的方向,我正在犯的错误。我在过去的两天里一直在努力,而且无法找到问题的解决方案。在此先感谢您的帮助。

2 个答案:

答案 0 :(得分:13)

您错误地设置了映射。 Hibernate抱怨没有名为departmentId的字段可用于建立一对一或多对关系,这是正确的。

您希望像这样映射您的值。

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;  
}

您将Department字段指向DepartmentHeadDepartmentHead字段内的Department字段。 Hibernate会排除要使用的ID,您不必在实际链接中指定它。

答案 1 :(得分:0)

学生班怎么样?您是否在Student类中定义了ManyToOne关系。

    @Entity
    public class Student {
      @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
      private int id;
      private String name;

      @ManyToOne
     private Department department;
     ..................

请检查this example