Wednesday, June 18, 2014

Difference between session.save() and session.persist() method of Hibernate.

6:14 PM



What is the difference between session.save() method and session.persist() method of hibernate API.

ses.save() & ses.persist() both methods are used to save/insert the record in database using hibernate specific persistence logic. 


Difference between session.save() and session.persist() method:


1.session.save() method returns generated identity value as the return value of the method call, as its return type is java.io.Serializable. Whereas session.persist() method does not returns anything as its return type is void.

2. Using the return value as result session.save() method call we can get to know what record value has been added into Database, moreover we can check if value has been added in database or not using if...else condition on returned value. 

3. session.save() method is useful on exception handling perspective but it take comparatively more time to execute than session.persist() method.

Example code using session.save() method.


import org.hibernate.*;
import org.hibernate.cfg.*;

class SaveDemo
{
public static void main(String[] args) 
{
Configuration cfg=new Configuration();
cfg=cfg.configure("Hibernate.cfg.xml");
SessionFactory sfactory=cfg.buildSessionFactory();
Session ses=sfactory.openSession();
Transaction tx=ses.beginTransaction();
EmpBean e=new EmpBean();
e.setId(101);
e.setEmail("diehardtechy@gmail.com");
int i=(Integer)ses.save(e);
if(i>0)
{
System.out.println("Record added to database "+" "+"Employee ID is : "+i);
}
else
{
System.out.println("Something strange has happend, need not to panic ! ");
}
tx.commit();
tx.close();
ses.close();
}
}


Example code using session.persist() method.


import org.hibernate.*;
import org.hibernate.cfg.*;

class PersistDemo
{
public static void main(String[] args) 
{
Configuration cfg=new Configuration();
cfg=cfg.configure("Hibernate.cfg.xml");
SessionFactory sfactory=cfg.buildSessionFactory();
Session ses=sfactory.openSession();
Transaction tx=ses.beginTransaction();
EmpBean e=new EmpBean();
e.setId(101);
e.setEmail("diehardtechy@gmail.com");
ses.persist(e); /* Does not return anything */
tx.commit();
tx.close();
ses.close();
}
}

Prototype of save() method: 

public Serializable save(Object object)throws HibernateException

Prototye of persist() method:

public void persist(Object object)throws HibernateException


If you run into problem or got more questions related to hibernate , feel free to ask in comment section. (If possible please attach screen shot of problem.)

0 comments :

Post a Comment

 

© 2014 DieHardTechy . All rights resevered. Designed by Diehardtechy