java - Null pointer exception in One To Many Mapping example -
employee class :
public class employee {
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 , setters
}
department class :
public class department {
private long department_id; private string department_name; private string department_location; private string department_rank; set<employee> employee_list; // getters , setters
}
impl class :
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(); }
}
even after adding whole set, getting null pointer exception @ line : department.getemployee_list().add(emp); getting wrong?
in department class, have not initialized set , have not done before persisting well.
so either set<employee> employee_list = new hashset<employee>();
in department class.
or below before persisting department object
department.setemployee_list(new hashset<>()); department.getemployee_list().add(emp);
Comments
Post a Comment