一对多映射示例中的空指针异常

时间:2014-05-18 17:00:42

标签: java hibernate

员工类:

公共类员工{

private int EMPLOYEE_ID;

private int FACULTY_NO;

private int ENROLMENT_NO;

private String FIRSTNAME;

private String LASTNAME;

private Date BIRTH_DATE;

private String CELLPHONE;

private Department DEP;

//getters and setters

}

系类:

公共类部门{

private Long DEPARTMENT_ID;

private String DEPARTMENT_NAME;

private String DEPARTMENT_LOCATION;

private String DEPARTMENT_RANK;

Set<Employee> EMPLOYEE_LIST;

    // getters and setters

}

IMPl类:

public class OneToManyImpl {

public static void main(String[] args) {

    SessionFactory sessionFactory = HibernateUtility.getSessionFactory();

    Session session = sessionFactory.openSession();

    session.beginTransaction();

    Department department = new Department();

    department.setDEPARTMENT_NAME("Mechanical Dept.");

    department.setDEPARTMENT_RANK("A class");

    department.setDEPARTMENT_LOCATION("University");
    session.save(department);


    Employee EMP = new Employee();
    EMP.setENROLMENT_NO(2007255);
    EMP.setENROLMENT_NO(3794);
    EMP.setFIRSTNAME("FirstName");
    EMP.setLASTNAME("Gernaline");
    EMP.setBIRTH_DATE(new Date());
    EMP.setCELLPHONE("011899954");
    EMP.setDEP(department);

    department.getEMPLOYEE_LIST().add(EMP);

        session.save(EMP);

        session.getTransaction().commit();

        session.close();

}

}

即使在添加整个Set之后,我也会在此行获得Null Pointer Exception:department.getEMPLOYEE_LIST()。add(EMP); 我哪里出错?

2 个答案:

答案 0 :(得分:0)

您未在EMPLOYEE_LIST初始化department

 department.setEMPLOYEE_LIST(new HashSet<>()); // You can add this line
 department.getEMPLOYEE_LIST().add(EMP);

答案 1 :(得分:0)

在你的部门课程中,你没有初始化集合,也没有在持久化之前完成它。

所以要么在部门班做Set<Employee> EMPLOYEE_LIST = new HashSet<Employee>();

或在持久化部门对象之前执行以下操作

department.setEMPLOYEE_LIST(new HashSet<>());
department.getEMPLOYEE_LIST().add(EMP);