簡體   English   中英

休眠中的OneToMany問題

[英]OneToMany issue in 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);

這段代碼中有很多問題。

第一個問題:未知實體:org.springmvc.form.Department。 這意味着Department不會用@Entity注釋和/或未在休眠配置文件的實體中列出。

第二個問題:

@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名員工。 那會破壞應用程序的性能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM