CRUD with Java, Hibernate and MySQL — Part 3
In Part 3 of this tutorial, we perform CRUD operations using Hibernate and MySQL. For more information about the Student object and Object-Relational Mapping, please refer to Part 2 of this tutorial.
Creating objects
Creating new records in the database can be achieved in three steps:
Creating a session factory. Here, we specify the hibernate configuration file and the entity class.
SessionFactory sessionFactory = new Configuration().configure(“hibernate.cfg.xml”).addAnnotatedClass(Student.class).buildSessionFactory();
Getting the current session
Session session = sessionFactory.getCurrentSession();
Creating a new Student object and saving it to the database
//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();
The complete code snippet can be found here.
Reading objects
Reading existing record from the database can be achieved in three steps:
Creating a session factory
SessionFactory sessionFactory = new Configuration().configure(“hibernate.cfg.xml”).addAnnotatedClass(Student.class).buildSessionFactory();
Getting the current session
Session session = sessionFactory.getCurrentSession();
Using the student id to retrieve the student
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();
The complete code snippet can be found here.
Updating objects
Hibernate uses its own query language called Hibernate Query Language (HQL) which is similar in appearance to SQL. More information can be found here.
Updating existing records from the database can be achieved in three steps:
Creating a session factory
SessionFactory sessionFactory = new Configuration().configure(“hibernate.cfg.xml”).addAnnotatedClass(Student.class).buildSessionFactory();
Getting the current session
Session session = sessionFactory.getCurrentSession();
Update records in the database using session.createQuery(“<your HQL update query>”).executeUpdate()
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();
The complete code snippet can be found here.
Deleting objects
Deleting rows from the database can be achieved in three steps:
Creating a session factory
SessionFactory sessionFactory = new Configuration().configure(“hibernate.cfg.xml”).addAnnotatedClass(Student.class).buildSessionFactory();
Getting the current session
Session session = sessionFactory.getCurrentSession();
Delete student based on id. Again, we make use of session.createQuery(“<your HQL delete query>”).executeUpdate()
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();
The complete code snippet can be found here.
For the complete source code, please take a look at my GitHub repository:
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.
Do you wish to improve your problem-solving skills for coding interviews? Do you struggle to apply data structures and algorithms while solving a problem? Sign up for AlgoExpert.io. I can personally attest that having gone through the questions and video explanations, they are the best resource for coding interview preparation on a tight time frame.
Use promo code: nwpxi-35 to get a 30% discount on AlgoExpert 1-year subscription.
Feel free to leave your comments or feedback in the responses below. If you do like this post, don’t forget to hit the clap icon below.
Thank you for reading. Happy coding!