Home Hibernate Hibernate : Session Save
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Hibernate : Session Save

Advertisement
In this section we will discuss how session.save() works in Hibernate.

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

Click here to download complete source code

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 16, 2012

Ask Questions?    Discuss: Hibernate : Session Save  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com