1、在學習Hibernate多對多關系的時候遇到了一下異常:

主函數出現了空指針異常:
public static void testadd() {
Session session = HibernateUtils.openSession();//獲得session
Transaction transaction = session.beginTransaction();//開啟事務
Student student=new Student();
student.setSname("翟");
student.setPoint(123f);
student.setClassno(46);
student.setSex("男");
student.setBirthday("2019-11-11");
student.setPhone("18739496522");
student.setEmail("34288334@qq.com");
Student student1=new Student();
student1.setSname("翟hb");
student1.setPoint(666f);
student1.setClassno(46);
student1.setSex("女");
student1.setBirthday("2019-11-11");
student1.setPhone("18739496522");
student1.setEmail("34288334@qq.com");
Course course=new Course();
course.setCourseno("123");
course.setCname("算法設計");
course.setType("必修");
course.setCredit(4);
course.setPeriod(22);
Course course1=new Course();
course.setCourseno("456");
course1.setCname("網絡");
course1.setCredit(2);
course1.setPeriod(12);
course1.setType("必修");
System.out.println(student);
System.out.println(student1);
System.out.println(course);
System.out.println(course1);
student.getCourses().add(course);
student.getCourses().add(course1);
student1.getCourses().add(course);
student1.getCourses().add(course1);
session.save(student);
session.save(student1);
session.save(course);
session.save(course1);
transaction.commit();//提交事務
session.close();//關閉資源
}
但是執行輸出語句能夠正常輸出對象中的內容:

2、問題原因:

在實體中定義一對多關系的時候沒有創建對象,導致在主函數中不能獲取集合對象。
修改代碼:
public class Student { private Integer studentno; private String sname; private String sex; private String birthday; private Integer classno; private Float point; private String phone; private String email; private Set<Course> courses=new HashSet<Course>();//利用集合表達一個學生有多個課程
new出來一個對象之后,主函數可以正常的向里面添加數據。錯誤得以解決。
