Hibernate operations (Data Update) - Part 2

Hibernate is an object-relational mapping (ORM) library for the Java language. Hibernate provides data query and retrieval facilities that significantly reduce the development time. Hibernate facilitates you to develop persistent classes following an object-oriented styles such as inheritance, polymorphism, composition, association, and collections.

This article only concern about data update through hibernate. (Data insertion article can be found at Part 1 of this series)

And also I have to mention here this article not describing all the hibernate from the beginning. Therefore this is not the best way to start your first hibernate java project. Simply this article very much suitable for the people those who having basis of the hibernate.

To start these all the sample programs you should do the initial thing such as adding related jar files, referring those jars, establish MySql db connection(from eclipse or netbeans to view db's data), etc.


Initiating............
First let's create java class which used as a persistent class.
Create a java class named "Person.java"

package pkg;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Person {
 private int id;
 private String name;
 private int age;

 @Id
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

This class is now persistent class through annotations.
(This class is identical to the class that we used in part 1)

Data Update
Before writing codes for updating let me introduce the HQL for the hibernate. This HQL can be use to update the db. It is essential to get know about HQL  before move to further operations of hibernate.

HQL - The Hibernate Query Language
HQL is similar in appearance to SQL that can be used as a a powerful query language for Hibernate.HQL is a case insensitive query language. Therefore as an example the keyword fRoM, FrOm, from and FROM are identical for a query.

The first HQL query.

from
from is the simplest possible Hibernate query. Let's clarify this by using few examples.

from Person

This will return all the data from Person table. The equaling sql query is,

/*this is equaling sql query for 'from Person'*/
select * from Person

In order to refer to the Person in other parts of the query, you can assign an alias for Person using 'as' keyword.

from Person as P
/*Now P refer the Person table*/

Also this can be acquired without using 'as' keyword.

from Person P
/*Now P refer the Person table*/

Parameters
These parameters can be used within the the query to pass values when they are executing in the java program.

The sign  :  used to define the parameters.

from Person as p where p.id = :personId

Here 'personId' is a parameter. Now lets execute a HQL query in java. Basically to execute a HQL query the method 'createQuery' in the class 'org.hibernate.classic.Session' is used.

String searchId = "1";
String query = "from Person as p where p.id = :personId";

session.createQuery(query).setString("personId", searchId);

When call the method 'createQuery' the value of 'searchId' will assign to the parameter 'personId' in the query. Finally the query for execute is,

from Person as p where p.id = 1

Now let's combine update and these 2 concepts to execute the update query. 'createQuery' method can be used execute the update query. A update query uses the keyword 'update' as follows


'keyId' is a parameter for the query which can be used to pass a value when it execute.

The complete java program for the update is,

package pkg;

import java.util.Iterator;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestPerson {

    public static void main(String[] args) {
       
        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Person.class);
        config.configure("hibernate.cfg.xml");
       
        SessionFactory factory = config.buildSessionFactory();
             
        //beginning of the session
        Session session = factory.openSession();
        session.beginTransaction();//beginning of the transaction
       
        String name = "New_Milinda";//this is new name for 'id'
        String id = "1";//this is the key id for field being updated
       
        //create the update query
        String query = "update Person as p set p.name = :newName where p.id = :keyId";
       
        session.createQuery(query)
            .setString("newName", name)//this will set the string 'newName' to name variable
            .setString("keyId", id)
            .executeUpdate();
        

        session.getTransaction().commit();//end of transaction
        session.close();//end of  session
       
       
        }

}

After this code segment run the data's which having id equal 1 will change its name into 'New_Milinda'. Here I used 'where' keyword to implement the condition for the update. (similar method used in mysql queries)

Finally the query to be executed is,

update Person as p set p.name = New_Milinda where p.id = 1

Also this is the query after setting all the parameters(newName and keyId).


I hope to post more articles for other operations of hibernate such as
  • Data retrieve
  • Data delete
from the db. Will be soon........

Related posts

5 comments:

  1. awesome milinda..thanks a lot..this is really cool..searching internet dosent gave me a solution as clear as this much..thanks again..
    අපේ භාසාවෙන් කිව්වොත් ගොඩාක් පින්...

    ReplyDelete
  2. මට මේකට නම් දෙපාරක් ටැන්කු කියන්න හිතෙනව අලො...මම මේ මීට චුට්ටකට කලින් රොසීඉන්ඩියා එකෙ විදිහට අප්ඩෙට් එකක් කරල රොස් වෙලා හිටියේ..ඒක වැඩ කලාට මෙලො රහක් තිබ්බෙ නැ..ඔන්න දැන් මම රොසින්ඩියා එකෙ ඉතුරි ට්‍රාන්සැක්ශන් ඉගෙන ගන්න එක නැවැත්තුව මෙකෙන්ම ඉගෙන ගන්න හිතා ගෙන.

    ReplyDelete
  3. tnamks machan dis is realy cool and so helpful

    ReplyDelete
  4. Many thanks to the person who made this post; this was very informative for me. Please continue this awesome work..pcb suppliers

    ReplyDelete
  5. Have you ever ponder from where does sign in error occur on your Binance account? Is the password error behind it or you are typing the wrong email id. Whatever the possibilities could be, you Binance Support NUmber can always fix your problems under the assistance of a team of skilled executives by dialing Binance support number +1877-330-7540 . The team is responsive and avail the best solutions to the users at any time.

    ReplyDelete