Updating an object

Here, we look at how to get a record from the database and update the same record to the database. The main goal is to get Employee#2 and update the first name, aarush, to aarush_updated.

How to do it…

Here, we are trying to update an employee object having id equals 2.

The SQL query executed to achieve the same result is as follows:

UPDATE employee SET firstName='aarush_updated' WHERE id=2;

Now, let's take a look at how to do the same using hibernate.

Code

Enter the following code to update an object of the employee type, where id is 2:

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();

/* Line 3 */ Employee employee = (Employee) session.get(Employee.class, new Long(2));

System.out.println("
Old Employee...");
System.out.println(employee.toString());

session.getTransaction().begin();
/* Line 9 */ employee.setFirstName("aarush_updated");
/* Line 10 */ session.update(employee);
session.getTransaction().commit();

System.out.println("
Employee after Update...");
System.out.println(employee.toString());

session.close();
HibernateUtil.shutdown();

Output

The output will be as follows:

Hibernate: select employee0_.id as id0_1_, employee0_.department as department0_1_, employee0_.firstName as firstName0_1_, employee0_.salary as salary0_1_, department1_.id as id1_0_, department1_.deptName as deptName1_0_ from employee employee0_ left outer join department department1_ on employee0_.department=department1_.id where employee0_.id=?

Old Employee...

Employee
 id: 2
 first name: aarush
 salary: 35000.0
 department: developement
Hibernate: update employee set department=?, firstName=?, salary=? where id=?

Employee after Update...

Employee
 id: 2
 first name: aarush_updated
 salary: 35000.0
 department: developement

How it works…

Here, we used the update() method to update a record. The code written in the third line is used to get the particular employee for update. In the ninth line, we set a new name to the employee object and update it using the tenth line.

There's more...

In the preceding section, we used the update() method for updating a particular record. Apart from this method, hibernate will provide one more useful method called saveOrUpdate().

This particular method is used to save or update records. Hibernate updates the records for a given object if the identifier field is given. If an identifier is not given, then hibernate will insert a new record.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.61.170