Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Hibernate Hibernate4 Hibernate update Query

Related Tutorials


 
 

Share on Google+Share on Google+

Hibernate update Query

Advertisement
In this tutorial you will learn about an update query in Hibernate

Hibernate update Query

In this tutorial you will learn about an update query in Hibernate

This tutorial is based on how to write HQl update query in hibernate. In hibernate update query updates the data of the database table when (if any) modification is made to the records. A simple query for update may be written as :

update ClassName set propertiesName = 'valueOfPropertiesToChange' where propertiesName = 'valueOfProperties'

You may set the value using setParameter() method of Query.

Example :

An example is being given below is concerned to update the value of a column of a table after the data modification at run time. To do so at first I have created a table in MySQL named salesorder that contains the fields 'id', 'price', and 'purchaser' with some records in their respective fields. Then created a class that contains some data members, setter getting methods and constructors, this class is a POJO class which object will be persisted into the table salesorder. Now created a mapping file named salesorder.hbm.xml to map the class object with table and a configuration file named hibernate.cfg.xml using which Hibernate will create a connection pool and the required environment setup to work with the database. Finally created a class where we will obtain the configuration, create a SessionFactory and obtain a session using SessionFactory, create a Transaction within which we will try to change the existing data and updates using the update query and executeUpdate() method of Query. The value for changing will be given by user at run time.

Complete Code

Table salesorder

CREATE TABLE `salesorder` ( 
`id` int(15) NOT NULL auto_increment, 
`price` int(25) NOT NULL, 
`purchaser` varchar(25) default NULL, 
PRIMARY KEY (`id`) 
)

SalesOrder.java

package roseindia;

public class SalesOrder {
private int id;
private int price;
private String purchaser;

public SalesOrder()
{

}
public SalesOrder(int price, String purchaser)
{
this.price = price;
this.purchaser = purchaser;
}

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getPurchaser() {
return purchaser;
}
public void setPurchaser(String purchaser) {
this.purchaser = purchaser;
}
}

salesorder.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">
<class name="SalesOrder" table="salesorder">
<id name="id" type="int" column="id" >
</id>
<property name="price">
<column name="price" />
</property>
<property name="purchaser">
<column name="purchaser" />
</property>
</class>
</hibernate-mapping>

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>

HibernateUpdateQuery.java

package roseindia;

import java.util.Scanner;

import org.hibernate.Transaction;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUpdateQuery {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

public static void main(String args[])
{
Session session = null;
try
{
try
{
Configuration cfg = new Configuration();
cfg.addResource("roseindia/salesorder.hbm.xml");
cfg.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();
Scanner scan = new Scanner(System.in);
Transaction t = session.beginTransaction();
System.out.println("Enter id of purchaser to change the purchaser");
int id = scan.nextInt();
System.out.println("Enter purchaser name to change");
String purchaser = scan.next();
Query query = session.createQuery("update SalesOrder so set so.purchaser='"+ purchaser+"' where so.id= '"+id+"'");
int update = query.executeUpdate();
if(update == 0 || update == 1)
{
System.out.println(update + " row affected");
}
else
System.out.println(update + " rows affected");

System.out.println("Successfully updated");
t.commit();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
session.close();
}
}
}

Output :

1. salesorder table before making the modification

2. When you will execute the java file HibernateUpdateQuery.java (RightClick -> runAs -> Java Application) you will get the output as :

3. salesorder table after modification & updation

Download Source Code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: March 1, 2012

Related Tutorials

Discuss: Hibernate update Query  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com