Hibernate save Example - Rose India Hibernate 4 tutorials
In the last section you have learned how to create Hibernate application in Eclipse. We have also saved the object using the Session.save() method. Here in this section we will explain you about the Session object and its methods.
Download the source code of the example discussed here from First Hibernate Example Step by Step in Eclipse tutorial page.
How to save objects in Hibernate?
Hibernate is very easy tool for creating the database access code. Developers interacts with the runtime through Session interface. The Session interface is the main interface between Java applications and Hibernate runtime. The Session interface provides the methods for saving, querying, updating and deleting the data from the database.
Here are the methods of the Session interface of Hibernate:
- save() - Used to save the object
- update() - Updated the state of object in database
- delete() - Delete from underlying database
- createCriteria(String entityName) - For selecting data based on certain criteria
The Session interface is retrieved using following code:
Session session = sessionFactory.openSession();
Transaction Management
You can also start the transaction using following code:
sess.beginTransaction();
Here is the code for transaction management:
Session sess = factory.openSession(); Transaction tx; try { tx = sess.beginTransaction(); //do some work ... tx.commit(); } catch (Exception e) { if (tx!=null) tx.rollback(); throw e; } finally { sess.close(); }
Here is the complete code for saving the data in Hibernate based application:
package net.roseindia; import org.hibernate.Session; import org.hibernate.SessionFactory; import net.roseindia.model.*; /** * @author Deepak Kumar * Web: http://www.roseindia.net */ public class CreateData { public static void main(String[] args) throws Exception { SessionFactory sessFact = HibernateUtil.getSessionFactory(); Session session = sessFact.getCurrentSession(); org.hibernate.Transaction tr = session.beginTransaction(); Employee emp = new Employee(); emp.setEmpName("Deepak Kumar"); emp.setEmpMobileNos("000000"); emp.setEmpAddress("Delhi - India"); session.save(emp); tr.commit(); System.out.println("Successfully inserted"); sessFact.close(); } }
Above class creates the object of Employee entity, sets the values and finally calls the session.save(emp) to save the data.
Here is the code of the model class used in the example:
package net.roseindia.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * @author Deepak Kumar * Web: http://www.roseindia.net */ @Entity @Table(name = "employee") public class Employee implements Serializable{ @Id @GeneratedValue @Column(name="id") private int id; @Column(name="emp_name") private String empName; @Column(name="emp_address") private String empAddress; @Column(name="emp_mobile_nos") private String empMobileNos; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public String getEmpAddress() { return empAddress; } public void setEmpAddress(String empAddress) { this.empAddress = empAddress; } public String getEmpMobileNos() { return empMobileNos; } public void setEmpMobileNos(String empMobileNos) { this.empMobileNos = empMobileNos; } }
The code of hibernate.cfg.xml file used in the project:
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate4</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.connection.pool_size">10</property> <property name="show_sql">true</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.current_session_context_class">thread</property> <mapping class="net.roseindia.model.Employee" /> </session-factory> </hibernate-configuration>
Here is the code of utility class which contains a method to get the SessionFactory:
package net.roseindia; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; /** * @author Deepak Kumar * Web: http://www.roseindia.net */ public class HibernateUtil { private static final SessionFactory sessionFactory; private static ServiceRegistry serviceRegistry; static { try { Configuration configuration = new Configuration(); configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings( configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Throwable th) { System.err.println("Enitial SessionFactory creation failed" + th); throw new ExceptionInInitializerError(th); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
In this you have learned how to use Hibernate's session.save() method to save the data in our example program.