Difference between hibernate's save,update and saveOrUpdate() methods

September 27, 2008

Hibernate

Difference between hibernate’s save,update and saveOrUpdate() methods

Hibetnate has set of methods for saving and updating the values in the database. The methods look like same and difficult to differentiate between them if you are not inderstanding them clearly.

save – save method stores an object into the database. That means it insert an entry if the identifier doesn’t exist, else it will throw error. If the primary key already present in the table, it cannot be inserted.

update – update method in the hibernate is used for updating the object using identifier. If the identifier is missing or doesn’t exist, it will throw exception.

saveOrUpdate – This method calls save() or update() based on the operation. If the identifier exists, it will call update method else the save method will be called.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
 
/**
 * source : www.javabeat.net
 */
public class HibernateExample {
    public static void main(String args[]){
	Configuration configuration = new Configuration();
	SessionFactory  sessionFactory = configuration.configure().buildSessionFactory();
	Session session = sessionFactory.openSession();
	Transaction transaction = session.beginTransaction();
	transaction.begin();
	EmployeeInfo employeeInfo = new EmployeeInfo();
	employeeInfo.setSno(1);
	employeeInfo.setName("HibernateTestSave");
	session.save(employeeInfo);
	transaction.commit();
	session.close();
 
	session = sessionFactory.openSession();
	transaction = session.beginTransaction();
	transaction.begin();
	employeeInfo = new EmployeeInfo();
	employeeInfo.setSno(1);
	employeeInfo.setName("HibernateTestUpdate");
	session.update(employeeInfo);
	transaction.commit();
	session.close();
 
	session = sessionFactory.openSession();
 
	transaction = session.beginTransaction();
	transaction.begin();
	employeeInfo = new EmployeeInfo();
	employeeInfo.setSno(1);
	employeeInfo.setName("HibernateTestSaveOrUpdate");
	session.saveOrUpdate(employeeInfo);
	transaction.commit();
 
	session.close();
   }
}
email

Comments

comments

Related posts:

  1. Batch insert in Hibernate
  2. Hibernate basic configuration example
  3. Collection Mapping in Hibernate : one-to-many
  4. Comparison operators in Hibernate
  5. NULL and NOT NULL comparison in the Hibernate API

No comments yet.

Leave a Reply