Now, we will see how hibernate saves data to the database.
As we have seen above,
i.e. Say there is a java class Employee :
Similarly in the database there is a table EMPLOYEE :
So, what we are going to do is initialize some values to Employee object and with the help of Hibernate, we are going to push it to the EMPLOYEE table.
Below is the code:
1. In the first step we need to get the 'SessionFactory'. And, as we know the details of 'SessionFactory' is in the configuration file 'hibernate.cfg.xml'. So, we are using 'new Configuration().configure().buildSessionFactory()' to build the 'SessionFactory' first.
2. Then, we need to get the 'Session' object from the 'SessionFactory'.
3. Next, we use this 'Session' object and begin a transaction.
4. After that, we create an 'Employee' object, assign some values to it. Then we use the 'save()' method of the 'Session' to save the object to the database.
5. Then we commit the transaction which will finally commit the 'Employee' data to the database. And close the 'Session'.
So, the steps are simple.
1. Open a 'Session' from the 'SessionFactory'.
2. Then start a 'transaction' using that 'Session'.
3. Post which create an 'Employee' object, put values to it and then save the 'Employee' object using the 'save()' method of 'Session'.
4. Finally, commit the transaction using the 'commit()' method of 'Session'.
We need to keep in mind that whatever operations we perform(like saving to DB), it should be inside the 'transaction' of a 'Session'. In other words the operation should be inside
session.beginTransaction() and session.getTransaction().commit().