如果DB中的列为null时为if语句

时间:2016-04-12 07:57:01

标签: java spring hibernate

我正在制作一个使用hibernate和spring mvc来从db读取数据的网格库..我有2个表雇员,它有EPMID,EMPNAME,EMPAGE,SALARY,ADDRESS,department_id(引用部门表中的department_id)和有department_id和name的部门......这里是Department.java

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设置为

1 个答案:

答案 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 --- *\
}