2016-04-12 10 views
2

球員我正在做一個網格庫,使用休眠和彈簧mvc從數據庫讀取數據..我有兩個表員工有EPMID,EMPNAME,EMPAGE,SALARY,ADDRESS,department_id refrences在部門表),並已和部門標識名稱部門部門標識......這裏是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當父部門標識..一個空指針異常沒有發現發生..我想設置的部門標識等於16,而不是

回答

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