gpt4 book ai didi

java - hibernate 中的一对多问题

转载 作者:行者123 更新时间:2023-12-01 22:36:16 25 4
gpt4 key购买 nike

我有这样的模型:

@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 注释和/或没有在 hibernate 配置文件的实体中列出。

第二个问题:

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

这没有道理。目标实体显然是部门,而不是员工。 targetEntity 是无用的,除非字段的类型是抽象类或接口(interface),并且您需要告诉 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 名员工。这会降低应用程序的性能。

关于java - hibernate 中的一对多问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26829578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com