Newsletter

Example On Hibernate Update Query

Hibernate » on Jun 13, 2011 { 23 Comments } By Sivateja

This is the program to update an object (1 complete row) in the database, which is already persisted in the database, then we have the following two approaches…

Approach 1

Load that object from the database, and modify its values, now hibernate automatically modifies the values on to database also, when ever the transaction is committed.

Approach 2:

If we want to modify object in the database, then create new object with same id and we must call update() given by session interface.

Files required to execute this program..

  • Product.java (My POJO class)
  • product.hbm.xml (Xml mapping file )
  • hibernate.cfg.xml (Xml configuration file)
  • ClientProgram.java(java file to write our hibernate logic)

Related to approach 1:

Product.java (POJO)

package str;

public class Product{

	private int productId;
	private String proName;
	private double price;

	public void setProductId(int productId)
	{
	    this.productId = productId;
	}
	public int getProductId()
	{
	    return productId;
	}

	public void setProName(String proName)
	{
	    this.proName = proName;
	}
	public String getProName()
	{
	    return proName;
	}

	public void setPrice(double price)
	{
	    this.price = price;
	}
	public double getPrice()
	{
	    return price;
	}
}

 

Product.hbm.xml

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

<hibernate-mapping>
<class name="str.Product" table="products">

<id name="productId" column="pid"  />
<property name="proName" column="pname" length="10"/>
<property name="price"/>

</class>
</hibernate-mapping>

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>

<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>

<mapping resource="Product.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>

ClientProgram.java (* Recommended way)

package str;

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

public class ForOurLogic { 

	public static void main(String[] args)
	{

		Configuration cfg = new Configuration();
		cfg.configure("hibernate.cfg.xml"); 

		SessionFactory factory = cfg.buildSessionFactory();
		Session session = factory.openSession();
		Object o=session.load(Product.class,new Integer(105));
		Product s=(Product)o;

		Transaction tx = session.beginTransaction();	

//s.setStno(105);   should not update, because we loaded with that number right..?
		s.setPrice(4000);   // implicitly update method will be called..

		tx.commit();

		System.out.println("Object Updated successfully.....!!");
		session.close();
		factory.close();
	}

}

Notes:

  • See line number 20, actually there i tried to update Stno(105), we should not do this, because we have loaded the object from the database with his id number only, see line number 16, if we update hibernate will rises the exception
  • See line number 24 once we call the commit(), automatically update method will be called by hibernate.
  • When ever an object is loaded from the database then hibernate stores the loaded object in cache-memory maintained by session-interface
  • Once an object is loaded, if we do any modifications on that object by calling its setter methods, then these modification are stored in the object maintained by cache-memory
  • if we modify the loaded object for multiple times then also the modifications will be stored in object maintained by the cache-memory only.
  • when ever we issue commit() operation then hibernate verify whether any changes are there between the object stored in the cache and object in the database, if changes exists then hibernate automatically updates the database by generating any update operation.
  • What am saying is hibernate automatically maintains synchronization between cache-memory object and database table objects (rows)

Related to approach 2:

 package str;

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

public class ForOurLogic { 

	public static void main(String[] args)
	{

		Configuration cfg = new Configuration();
		cfg.configure("hibernate.cfg.xml"); 

		SessionFactory factory = cfg.buildSessionFactory();
		Session session = factory.openSession();	

		Product p=new Product();
		p.setProductId(104);  // 104 must be in the DB
		p.setProName("Someting");		

		Transaction tx = session.beginTransaction();
			session.update(p);
		tx.commit();

		System.out.println("Object Updated successfully.....!!");
		session.close();
		factory.close();
	}

}

 

Oracle DB, Before Run The Program

Oracle DB, After Run the program

Notes:

  • From line number 17 to 19, we created new object and modified, and in line number 22 we are calling update method explicitly
  • Here we no need to load an object from the database
  • we will create a new object, and we will assign same id no’s to it and we will call update() explicitly in order to make the changes on the object that is stored in the database

That’s it, actually first approach isΒ  recommended always.. Β  πŸ™‚

​ ​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

23 Responses to “Example On Hibernate Update Query”
  1. hi Java4s team ,
    https://www.java4s.com is very very best website for java developer. i have clear so many Java related doubts using this site .
    thanks and regard.
    Raju Kapadne

  2. Ganesh says:

    Hi…
    In ClientProgram.java (* Recommended way) , the line number 21 you commented s.setStno(105);
    In Product class there is no setStno() method. its setProductId() method right !
    Sorry. i am always commenting to show the mistakes .
    My intention is just to correct … so others can get more benefit from this tutorials …
    Hope you can take it positively …
    thank you…

  3. Java4s says:

    @Ganesh

    Thanks for the update πŸ™‚ no problem, i am really very happy to hear.
    While doing the application i have changed the method, no issues just change the method and carry on.

  4. Raghu says:

    in the second approach when i update price column also changing with value ZERO, may I know why than happen ,
    Thanks in advance

  5. What is synchronization in database please clear this topic.
    Thanks in Advance

  6. aspnetcs says:

    No row with the given identifier exists: [str.Product#105]

  7. This site is more useful.Thanks.

  8. Parveen Thakur says:

    Hi All,
    I want to know that we need to write
    session.update(p);
    Because when I am not using the above statement , I got updated object.

  9. Varan says:

    Hi,
    i got the problem in updating table
    i am using oralce11g
    i got the followng exception how to solve it plz help me
    Exception in thread “main” org.hibernate.HibernateException: Hibernate Dialect must be explicitly set at org.hibernate.dialect.DialectFactory.determineDialect(DialectFactory.java:57)
    at org.hibernate.dialect.DialectFactory.buildDialect(DialectFactory.java:39)
    at org.hibernate.cfg.SettingsFactory.determineDialect(SettingsFactory.java:422)
    at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:128)
    at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292)
    at hib.varan.UpdateClientLogic.main(UpdateClientLogic.java:13)

    • Dhirendra Kumar says:

      if you use oracle 10g database then use this dialect

      <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>

      or choose specific database dialect

  10. krishna says:

    @praveen

    Use oracleDialect

  11. Pallavi says:

    Hi ,

    I am getting following error:

    “Exception in thread “main” org.hibernate.QueryException: Expected positional parameter count: 1, actual parameters: [] [from Product p where p.pid = ?]” at the position where I query the database.

    I am not able to figure out why.

    Could you please tell me where I am going wrong.

  12. Venkat says:

    Hi,
    I have a doubt. Is it really necessary to provide configuration file name at the time of configuration.
    Configuration cfg = new Configuration();
    cfg.configure();

    I am able to run my program even if i did not gave the Configuration file name.

    • Harisai says:

      If hibernate.cfg.xml is available in src ,then compiler can itself take it as configuration file.

  13. Naga says:

    Can you please tell me how to do soft deletion in table using hibernate.Using if condition.

    we have to create entity class object and then we will get that entity reference then what is the process please help me i will strucked there.

  14. amit yadav says:

    Thanks in Advance..

    In second approch(Explicitly call update()) only one time my values are changing in db,

    But when i am try to update second time ,i am getting lock Exception that its saying it is try to update or delete by other transaction.

    • Sheelpriya says:

      Hi Amit,

      According to my analysis, u have followed second approch ,new object is created and set the value and call update but on second u should create the new object and set the value and call the update and commit the transaction.you have done the same thing or another?

  15. Neeraj says:

    If we call update method by creating object with already save id but object with same id not found during update call then will it make a new object with same id or some thing else

  16. naresh says:

    Superb man excellent java teaching style never ever will be seen in any blog or website. My whole-hearted thanks to you and your team

  17. Kalidas says:

    Hi Sir,

    Related to approach 2:
    If you are updating 2 properties only then another properties value is 0(default) value store into DB.
    See below example :
    Product p=new Product();
    p.setProductId(104); // 104 must be in the DB
    p.setProName("Someting");
    // Price = 0 i,e default(int/double) — if you are not p.setPrice() then update method set 0 in Price column
    // String store null
    @Java4s — In above Example Please Update Price i.e 0 by default

    Regards
    Kalidas Daundkar

    • swati says:

      p.setProductId(104); // 104 must be in the DB
      p.setProName("Someting");
      you have mentioned productId(104) and it has updated at (105).
      I am confused. Please clear!

  18. Sridharan Mohan says:

    <<
    if we modify the loaded object for multiple times then also the modifications will be stored in object maintained by the cache-memory only.
    when ever we issue commit() operation then hibernate verify whether any changes are there between the object stored in the cache and object in the database, if changes exists then hibernate automatically updates the database by generating any update operation.
    >>

    What if tried to change the value and reverting the same value and trying to commit at last?
    i.e no change in the POJO now.
    So will the Hibernate execute and make change in DB without modifying any columns?

  19. Mohit says:

    What if i have to join 2 tables and multiple where clause

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.