If the name of the config file is not given, Hibernate will automatically look for a file on your class path called hibernate.cfg.xml.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Session session = factory.getCurrentSession(); try{ // use the session objection to save Java Object System.out.println("Creating a new student object..."); Student tempStudent = new Student("Paul", "Wall", "Paul@test.com");
// Create the student object session.beginTransaction();
// save the student object System.out.println("Saving a student..."); session.save(tempStudent);
Clean up the table and the index will start from 1.
Read Objects
Retrieve from the database using the PK.
1 2 3 4 5 6 7 8 9 10 11
// get a new session and start a transaction session = factory.getCurrentSession(); session.beginTransaction();
// retrieve a student based on the PK System.out.println("\nGetting Student with id: "+ tempStudent.getId()); Student myStudent = session.get(Student.class, tempStudent.getId()); System.out.println("Get Completed:" + myStudent);
// commit the transaction session.getTransaction().commit();
Querying Objects
1
List<Student> theStudents = session.createQuery("from Student s where s.lastName = 'Zhang'").getResultList();
Update Objects
1
session.createQuery("update Student set email='dylan@gmail.com' where firstName='Dylan'").executeUpdate();
Delete Objects
1 2 3 4 5 6
// retrieve a student int studentId = 5; Student myStudent = session.get(Student.class, studentId);
// delete session.delete(myStudent);
1
session.createQuery("delete from Student where id=1").executeUpdate();
Reference: Udemy, Spring & Hibernate for Beginners (including SpringBoot)