gpt4 book ai didi

java - Hibernate 应用程序中 OneToMany 关联集合为 null

转载 作者:行者123 更新时间:2023-12-01 13:05:08 27 4
gpt4 key购买 nike

我正在开发一个简单的 Hibernate 应用程序来测试 OneToMany 关联。我使用的实体是EmployeeDepartment,其中有许多Employees:

@Entity
public class Department {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long departmentId;

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

...
getters/setters

}

@Entity
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long employeeId;

@ManyToOne
@JoinColumn(name="employee_fk")
private Department department;

...
getters/setters

}

我创建一些记录:

tx.begin();

Department department = new Department();
department.setDepartmentName("Sales");
session.persist(department);

Employee emp1 = new Employee("Ar", "Mu", "111");
Employee emp2 = new Employee("Tony", "Almeida", "222");
Employee emp3 = new Employee("Va", "Ka", "333");

emp1.setDepartment(department);
emp2.setDepartment(department);
emp3.setDepartment(department);


session.persist(emp1);
session.persist(emp2);
session.persist(emp3);

Set<Employee> emps = department.getEmployees();
emps.remove(emp2);

但是在最后一行: emps.remove(emp2); 我收到一个 NullPointerExceptionemps 集合即 。我尝试通过以下方式更改关联的所有者:

 @Entity
public class Department {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long departmentId;

@OneToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name="department_fk")
private Set<Employee> employees;

...
getters/setters

}

@Entity
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long employeeId;

@ManyToOne
@JoinColumn(name="department_fk", insertable=false, updatable=false)
private Department department;

...
getters/setters

}

但是结果是一样的。为什么EmployeesSet没有创建。为了使其发挥作用,必须改变什么?

最佳答案

自己初始化集合,可以在构造函数中或通过指定字段的初始值。

事实上,当您从数据库中获取对象时,Hibernate 会将集合初始化为空集合。但是,当您自己创建对象并持久化它时,Hibernate 不会真正接触您创建的对象,而只会持久化它,因此在这种情况下它不会为您初始化该字段。

如果你想确保该字段永远不为空(我同意这是可取的),只需自己确保它,甚至在坚持之前。

关于java - Hibernate 应用程序中 OneToMany 关联集合为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23323881/

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