CRUD with Java, Hibernate and MySQL — Part 3

Creating objects

SessionFactory sessionFactory = new Configuration().configure(“hibernate.cfg.xml”).addAnnotatedClass(Student.class).buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
//create the Student object
Student student = new Student("Paul", "Walker","paul.walker@gmail.com");
//start a transaction
session.beginTransaction();
//Save the Student object to the database
session.save(student);
//commit the transaction
session.getTransaction().commit();

Reading objects

SessionFactory sessionFactory = new Configuration().configure(“hibernate.cfg.xml”).addAnnotatedClass(Student.class).buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();//Read the student
System.out.println(“Getting the student based on id: “ + student.getId());
Student readStudent = session.get(Student.class, student.getId());//specify PRIMARY KEY of the studentSystem.out.println(“Retrieved student : “ + student);//commit the transaction
session.getTransaction().commit();

Updating objects

SessionFactory sessionFactory = new Configuration().configure(“hibernate.cfg.xml”).addAnnotatedClass(Student.class).buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();//update email for all students
int rowsUpdated = session.createQuery(“update Student set email=’hiberate@gmail.com’”).executeUpdate();
System.out.println(“Rows updated : “ + rowsUpdated);session.getTransaction().commit();

Deleting objects

SessionFactory sessionFactory = new Configuration().configure(“hibernate.cfg.xml”).addAnnotatedClass(Student.class).buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
int studentId = 3000;//Deleting a single student
session.beginTransaction();
System.out.println(“Retrieving student with id : “ + studentId);Student readStudent = session.get(Student.class, studentId); //specify PRIMARY KEY of the studentsession.delete(readStudent);delete Student id=3001
System.out.println(“Deleting student where id=3001”);
session.createQuery(“delete from Student where id=3001”).executeUpdate();//commit the transaction
session.getTransaction().commit();

Credits: The example in this article was inspired from a Spring & Hibernate For Beginners course by Chad Darby on Udemy.

Disclaimer: The aim of this article is to explain a complex topic in a short time for the reader and is in no way, shape or form intended towards discrediting the instructor’s work.

--

--

https://linktr.ee/amrutpatil | Entrepreneur | Instructor | Thinker | Cloud Architect (9–5) | 3x AWS Certified | Exploring business building & digital marketing

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store