Online Training Spring Hibernate Training in Delhi R Programming Training Course Big Data and Hadoop Training Java Training

Hibernate saveOrUpdate Method

In this tutorial you will learn about the saveOrUpdate method in Hibernate.

Ads

Tutorials   
How to write hello world example program in Hibernate? How to create one to one relationship in Hibernate 4 with Annotation? How to calculate minimum in Hibernate using the min() Function Hibernate 4.3.4 Released: Hibernate 4.3.4.Final Maven dependency Hibernate 4.3 Hello World: Example How to create SessionFactory in Hibernate 4.3.1? Hibernate 4 Hello World: Example of Hello World program Hibernate 4 create Session Factory: Example of creating Session Factory in Hibernate 4 Hibernate 4.3 and JPA 2.1 Example What is Hibernate in Java? Hibernate Overview and Architecture What is JPA 2.1? Hibernate 4.3.0.Final Maven dependency Hibernate 4.3 ORM Features Hibernate 4.3 Tutorial Hibernate Criteria average example Hibernate Criteria load all objects from table Hibernate Criteria Hibernate beginner tutorial Hibernate Session.delete() Example Hibernate save or update method example Hibernate Load Example Hibernate save Example - Rose India Hibernate 4 tutorials Hibernate Example Step by Step in Eclipse Hibernate Configuration files Setup Hibernate Environment Hibernate Architecture Hibernate Overview Hibernate 4.2 Tutorial Hibernate 4 Annotations Tutorial Hibernate 4 AnnotationSessionFactoryBean hibernate versions hibernate jndi hibernate tomcat hibernate metamodel generator hibernate entity Seam Hibernate C3P0 Hibernate hibernate shard hibernate means temporal hibernate jsf hibernate spring j2ee hibernate spring hibernate encrypted password alias_to_entity_map hibernate temporal jsf spring hibernate hibernate by example hibernate repository hibernate sample code
Ads

Hibernate saveOrUpdate Method

In this tutorial you will learn about the saveOrUpdate method in Hibernate.

Hibernate's saveOrUpdate method inserts the new record and updates the modified value into the table. Using this method you can do the both insert data to the table and update the table with the modification made in the existed identifier. This method inserts the record to the table as a new record if the record provided by you is not existed and updates the table as well as it replaces the value that you are tried to update with the existed identifier. In short this method calls the save() method if an identifier is not existed and calls update() method if an identifier is existed.

Example :

Here is a basic example which will demonstrate you how saveOrUpdate() method can be used in Hibernate. For this I am giving a complete source code which can be downloaded. To achieve the solution of our problem at first I have created a table in MySQL named person with the fields Id, Name and PersonType and then created a POJO / Persistent class named Person.java to fetch the persistent object, a hibernate.cfg.xml file that the Hibernate can utilize it to create connection pool and the required environment setup, an person.hbm.xml file to map a Person object with table person. And finally create a simple java file using which we will use a saveOrUpdate() method of Hibernate to insert and update the record of table according to the identifier.

Complete Code :

Person.java

package roseindia.net;

public class Person {
private int id;
private String name;
private String type;

public Person()
{

}
public Person(String name, String type)
{
this.name = name;
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}

person.hbm.xml

<?xml version='1.0'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="roseindia.net">
<class name="Person" table="person">
<id name="id" type="int" column="Id" >
<generator class="assigned"/>
</id>
<property name="name">
<column name="Name" />
</property>
<property name="type">
<column name="PersonType" />
</property>
</class>
</hibernate-mapping>

PersonSaveOrUpdate.java

package roseindia.net;

import java.util.Scanner;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class PersonSaveOrUpdate {

private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

public static void main(String args[]) {
Session session = null;
try {
try {
Configuration cfg = new Configuration().addResource(
"roseindia/net/person.hbm.xml").configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
cfg.getProperties()).buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);

} catch (Throwable th) {
System.err.println("Failed to create sessionFactory object."
+ th);
throw new ExceptionInInitializerError(th);
}
session = sessionFactory.openSession();
Person person = new Person();
Scanner scan = new Scanner(System.in);
Transaction tr = session.beginTransaction();
System.out.println("Enter PerId No. : ");
int id = scan.nextInt();
System.out.println("Enter the PerName : ");
String name = scan.next();
System.out.println("Enter the type of Person : ");
String type = scan.next();
person.setId(id);
person.setName(name);
person.setType(type);
session.saveOrUpdate(person);
System.out.println("Successfully updated");
tr.commit();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/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://192.168.10.13:3306/data
</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>
</session-factory>

</hibernate-configuration>

Output :

When you will execute the java file PersonSaveOrUpdate.java you will get the output as :

1. A person table before entering the record using Hibernate :

2. Inserts a new record using java program as follows :

3. When you will provide the value as on look at on console then the output will be as :

4. New records will be inserted into the table and the table will be look as :

5. When you will provide the record with an existing identifier then the new value will be replaced by an existing value.

6. And the table will look as :

Download Source Code.

Advertisements

Share on Google+Share on Google+

Hibernate saveOrUpdate Method

Posted on: February 24, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: Hibernate saveOrUpdate Method  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
Brijmohan sharma
March 6, 2013
not work code hibernate SaveOrUpdate code

it is given the error: Hibenate.hbm.xml not found: what can i do?

Ads

 

Ads