Hibernate : Session Save
In this section we will discuss how session.save() works in Hibernate.
Hibernate session.save() :
save() method is used for saving the object of your persistent class into database table.It inserts object and fails if primary key already exist. session.save() returns the generated identifier (Serializable object)
Syntax : save(Object object) throws HibernateException
Parameters: object - a transient instance of a persistent class
Returns: generated identifier
Throws: HibernateException
Example : In this example we are saving employee record by using session.save() method.
Here is main class code -
package net.roseindia.main; import net.roseindia.table.Employee; import net.roseindia.util.HibernateUtil; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; public class HibernateSessionSave { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Employee employee = new Employee(); employee.setName("Lizza"); employee.setSalary(25000); session.save(employee); transaction.commit(); System.out.println("Employee record saved"); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } }
Output :
Hibernate: insert into employee (date_of_join, name, salary) values (?, ?, ?) Employee record saved