Hibernate(Session Factory)::Doing the same as my Udemy teacher but mine one doesnt work?

41 Views Asked by At

I am doing this course from udemy .Just a beginner in spring and hibernate. I tried every method available at internet but not working.Everytime the errors points at "SessionFactory factory = new Configuration()"

   public class CreateStudentDemo {

    public static void main(String[] args) {

        // create session factory
        System.out.println("Project started");
        SessionFactory factory = new Configuration()
                .configure("hibernate.cfg.xml")
                .addAnnotatedClass(Student.class)
                .buildSessionFactory();

        // create session
        Session session = factory.getCurrentSession(); 

        try{
            System.out.println("Creating new student object....");
            Student tempStudent = new Student("Paul", "Wall", "[email protected]");
            session.beginTransaction();
            System.out.println("Saving the student..");
            session.save(tempStudent);
            session.getTransaction().commit();
            System.out.println("Done!");
        } finally {
            factory.close();
        }

    }

}
1

There are 1 best solutions below

0
ilia On

I hope you already solved the problem, but just in case here is the main factor of the problem. When you do the first new Configuration() most probably it imported something different Configuration() instead of hibernate root one.

Configuration() should import this root

import org.hibernate.cfg.Configuration;

Then it will work

 SessionFactory factory =new Configuration()
                .configure("hibernate.cfg.xml")
                .addAnnotatedClass(Student.class)
                .buildSessionFactory();

Check the picture