public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "department_id")
private int depId;
@Column(name = "name")
private String depName;
@OneToMany(mappedBy="department",cascade = { CascadeType.ALL }, orphanRemoval=true)
private List<Employee> employees;}
Employee.java
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "EMPID")
private int empId;
@Column(name = "EMPNAME")
private String empName;
@Column(name = "ADDRESS")
private String empAddress;
@Column(name = "SALARY")
private String salary;
@Column(name = "EMPAGE")
private int empAge;
@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="department_id")
private Department department;}
以及在服务中添加员工的功能
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false)
public void addEmployee(String[] list, Employee employee) {
employee.setEmpName(list[2]);
employee.setEmpAge(Integer.parseInt(list[4]));
employee.setEmpAddress(list[6]);
employee.setSalary(list[1]);
//employee.getDepartment().setDepId(Integer.parseInt(list[3]));
Department dept = departmentDao.getDepartment(Integer.parseInt(list[3]));
if(dept.equals(null)){
employee.setDepartment(departmentDao.getDepartment(16));
}
employee.setDepartment(dept);
this.employeeDao.addOrEditEmployee(employee);
}
但是当输入未在父department_id中找到的department_id时,会发生nullpointer异常..我想将department_id等于16设置为
答案 0 :(得分:-1)
默认情况下,Java中的每个类都有java.lang.Object
作为其超类。由于equals
方法由Object类提供,因此您可以在dept
对象上调用它。
if (dept.equals(null)) {
employee.setDepartment(departmentDao.getDepartment(16));
}
null不是Java中的对象。所以if语句应该是:
if(dept == null) {
\* ---- your code goes here --- *\
}