Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com
Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

Tuesday, July 8, 2014

Difference between session.update() , session.merge() and session.saveOrUpdate() method of hibernate API.


What is the difference between session.update(Object obj), session.merge(Object obj) and session.saveOrUpdate(Object obj) method of hibernate API?

session.update(), session.merge() and session.saveOrUpdate() all three methods are used to update the records in database using hibernate persistence logic.


List of differences :

session.update(Object obj) method will update the record if the record is found in database, if record is not found in database it will throw an unchecked exception.it will not return anything as part of method call because its return type is void.

session.merge(Object obj) method will update the record if the record is found in database, if record is not found in database it will add that particular record in table, also it returns a persistent object of java pojo class whose object is going to insert in table. 

session.saveOrUpdate() method will update the record if the record is found in database, if record is not found in database it will add that particular record in table, but does not returns any thing as result of method call because its return type is void.

Prototype of session.update(Object object) method

public void update(Object object)throws HibernateException

Prototype of session.saveOrUpdate(Object object) method


public void saveOrUpdate(Object object)throws HibernateException

Prototype of session.merge(Object object) method


public Object merge(Object object)throws HibernateException

Example using session.update(Object obj) method:

import org.hibernate.*;
import org.hibernate.cfg.*;         
public class TestClient 
{
          public static void main(String[] args) 
          {
                   Configuration cfg= new Configuration();
                   cfg=cfg.configure("Hibernate.cfg.xml");
                   SessionFactory factory=cfg.buildSessionFactory();
                   Session ses=factory.openSession();
                   Transaction tx=ses.beginTransaction();
                   EmpBean eb2=new EmpBean();
                   eb2.setNo(125);
                   eb2.setFname("die");
                   eb2.setLname("hard");
                   eb2.setMail("diehardtechy@gmail.com"); 
                   ses.update(eb2); 

/* If record 125 is found in table then it will update the record , otherwise it will throw an exception. */

                   tx.commit();
                   ses.close();
                   factory.close();

          }
}

If record not found in database


Example using session.saveOrUpdate(Object obj) method:


import org.hibernate.*;
import org.hibernate.cfg.*;         
public class TestClient 
{
          public static void main(String[] args) 
          {
                   Configuration cfg= new Configuration();
                   cfg=cfg.configure("Hibernate.cfg.xml");
                   SessionFactory factory=cfg.buildSessionFactory();
                   Session ses=factory.openSession();
                   Transaction tx=ses.beginTransaction();
                   EmpBean eb2=new EmpBean();
                   eb2.setNo(125);
                   eb2.setFname("die");
                   eb2.setLname("hard");
                   eb2.setMail("diehardtechy@gmail.com"); 
                   ses.saveOrUpdate(eb2); 

/* If record 125 is found in table then it will update the record , otherwise it will add the record in the table. */
                   tx.commit();
                   ses.close();
                   factory.close();

          }
}

Example using session.merge(Object obj) method:

import org.hibernate.*;
import org.hibernate.cfg.*;         
public class TestClient 
{
          public static void main(String[] args) 
          {
                   Configuration cfg= new Configuration();
                   cfg=cfg.configure("Hibernate.cfg.xml");
                   SessionFactory factory=cfg.buildSessionFactory();
                   Session ses=factory.openSession();
                   Transaction tx=ses.beginTransaction();
                   EmpBean eb2=new EmpBean();
                   eb2.setNo(125);
                   eb2.setFname("die");
                   eb2.setLname("hard");
                   eb2.setMail("diehardtechy@gmail.com"); 
                   EmpBean ee=(EmpBean)ses.merge(eb2); 

/* If record 125 is found then it will update the record in db, otherwise it will add that record in database, it doesn't throw any exception if the record in not found. Also it returns the persistence pojo class object whose record is going to be inserted in DB.*/

                   System.out.println(ee);
                   tx.commit();
                   ses.close();
                   factory.close();

          }
}

All the above example java program are based upon the assumption that you have EmpBean.java as pojo class. If you don't have the EmpBean.java class or you are new to hibernate you can first read our article on How to start with Hibernate.


Wednesday, June 18, 2014

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



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.)

How to run first program of Hibernate : A beginner's guide

Before we proceed further on how to start with hibernate and how to execute your first hibernate program.Please make sure that you have following software ready.

1. Java 1.6 or +
2. MySQL 5 or +/Oracle 10G

Make sure you have Employee table with eid, first_name, last_name. email column. 

Step by step procedure of how to run first hibernate program

  1. Download latest version of hibernate software (jar files) from http://sourceforge.net/projects/hibernate/

  2. Unzip the zip file which you downloaded in step 1.

  3. Add all jar files of hibernate-search-4.5.1.Final\dist\lib\required folder to class path,separated by semi colon.

  4. Add jar files of hibernate-search-4.5.1.Final\dist folder to class path, separated by semi colon.

  5. If you are using Oracle as your database then also add oracle related jar file to class path.

  6. Create a directory for all hibernate related programs you will practice from here onward.
Your directory structure should look like this.


  • EmpBean.java is a simple Java file which have getter and setter methods.(All members of this class should be non-static only)

  • Hibernate.cfg.xml is a hibernate configuration file, which contains property related information.Like DB software related url, driver information etc.

  • Hibernate.map.xml is a hibernate mapping file, which is used to map java pojo class(EmpBean.java) members with Database table column.

  • FirstProgram.java is a java file which contains hibernate based persistence logic.

Download above mentioned all 4 file here: 

Compile both java file and run.

If you run into any problem , feel free to ask .(If possible attach screen shot of the problem)