在休眠中出现OneToMany问题

时间:2014-11-09 15:03:21

标签: java hibernate

我有这样的模特:

@Table(name="EMPLOYEE")
public class Employee {

 @Column(name="firstname")
 private String firstname;


  // and others 

    @ManyToOne( targetEntity = Employee.class,
      fetch=FetchType.EAGER, cascade=CascadeType.ALL)
    @JoinColumn(name="department_id", 
            insertable=false, updatable=false, 
            nullable=false)
 private Department department;

=============================================== ==============================

  @Table(name="DEPARTMENT")
  public class Department {

    @Column(name="DEPARTMENT_ID")
    private Long departmentId;


   @OneToMany( targetEntity = Employee.class,
        fetch=FetchType.EAGER, cascade=CascadeType.ALL)
   @JoinColumn(name="department_id")
   @IndexColumn(name="idx")
   private List<Employee> employees; 

和我的DepartmentDaoImpl是

  public class DepartmentDaoImpl implements DepartmentDao{
  @Autowired
  private SessionFactory sessionFactory;
  @Transactional
  public void addDepartment(Department department) {
    sessionFactory.getCurrentSession().save(department);
}

当我运行项目时,此异常出现在输出

org.hibernate.MappingException: Unknown entity: org.springmvc.form.Department
这是什么问题以及如何解决的?

 Department department = new Department();
    department.setDepartmentName("Sales");
    department.setDepartmentId(90);

    Employee emp1 = new Employee("reza", "Mayers", "101",department.getDepartmentId());
   // Employee emp2 = new Employee("ali", "Almeida", "2332");

    department.setEmployees(new ArrayList<Employee>());
    department.getEmployees().add(emp1);

1 个答案:

答案 0 :(得分:3)

此代码中存在许多问题。

第一个问题:未知实体:org.springmvc.form.Department。这意味着Department未使用@Entity注释和/或未在hibernate配置文件中的实体中列出。

第二个问题:

@ManyToOne( targetEntity = Employee.class)
private Department department;

这没有意义。目标实体显然是部门,而不是员工。除非字段的类型是抽象类或接口,否则targetEntity是无用的,并且您需要告诉Hibernat它应该使用什么作为具体的实体类。否则,Hibernate会从字段类型中知道目标实体。

第三个问题:

@OneToMany( targetEntity = Employee.class,
    fetch=FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name="department_id")

此OneToMany是您已在Employee中声明和映射的双向关联的反面。所以你不能在这里重复映射。相反,您必须使用mappedBy属性声明它为反面:

@OneToMany(mappedBy = "department", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
@IndexColumn(name="idx")
private List<Employee> employees;

使用渴望获取toMany关联也是一个非常糟糕的主意。每次加载部门时,您真的不想加载部门的200名员工。这会破坏你的应用程序的性能。