小编典典

AnnotationException引用的属性不是(One | Many)ToOne

hibernate

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

AnnotationException Referenced property not a (One|Many)ToOne
on
com.student.information.service.Department.departmentId in mappedBy of com.student.information.service.DepartmentHead.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:引用的属性不是(One | Many)ToOne:

有人能指出我在犯什么错误的正确方向吗?我从过去的2天开始苦苦挣扎,无法解决问题的解决方案。在此先感谢您的帮助。


阅读 1161

收藏
2020-06-20

共1个答案

小编典典

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

您想要这样映射您的值。

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,而无需在实际链接中指定该ID。

2020-06-20