Hibernate学习:Exception in thread "main" java.lang.NullPointerException

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出来一个对象之后,主函数可以正常的向里面添加数据。错误得以解决。

posted @ 2019-11-16 10:14  怀梦想,致远方  阅读(521)  评论(0编辑  收藏  举报