【发布时间】:2014-04-27 13:14:46
【问题描述】:
我正在开发一个简单的Hibernate 应用程序来测试OneToMany 关联。我使用的实体是Employee 和Department,其中有很多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); 我收到一个NullPointerException,emps 集合就是null。我已尝试通过以下方式更改关联的所有者:
@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
}
但是结果相同。为什么没有创建Employees 的Set。必须进行哪些更改才能使其正常工作?
【问题讨论】:
标签: java hibernate nullpointerexception associate