Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updating a field of a object in hibernate

I have a object A which maps to table A in DB

class A {
     Integer id;
     String field2,field2;field3 ,... fieldN;
     //lots of other attribute
}

Now i want to write a DAO api that just updates a single field.One approach is that i can first load the object then changes the attribute i need and then use merge api

//start transcation
A a = session.load(A.class, id);
A.setfieldP(newValue)
session.merge(A)
//commit transcation

Now if i use following code

 //start transcation
 A a = new A();
 a.setId(id); //set a id by which object A exists in DB
 A.setfieldP(newValue)
 session.merge(A)
 //commit transaction

Now second approach all fields except id and fieldP are set to null

1)Now is there any other approach?
2)Can i use update instead of merge ?

like image 492
akshay Avatar asked Jul 22 '11 13:07

akshay


4 Answers

If you need to update lots of entities at once the most efficient way is to use a query:

Query query = session.createQuery("update EntityName set fieldP = 'newValue' "
        + "where id IN (75, 76)");
query.executeUpdate();

This allows you to change field values without loading the entity or entities into memory.

It is best practice is to use named queries and named parameters - the above implementation is just an example.

like image 137
Russ Hayward Avatar answered Oct 30 '22 09:10

Russ Hayward


I usually prefer session.get vs session.load, as session.get will return null as opposed to throwing an exception, but it depends on the behavior you want.

loading the object, setting your field, and calling either

 session.merge(myObject)

is the standard way, although you can also use

 session.saveOrUpdate(myObject)

as long as the object hasn't been detached, which in your case, it won't have been detached. Here is a good article explaining the differences in merge and saveOrUpdate.

In your second example, you are editing the primary key of the object? This is generally bad form, you should delete and insert instead of changing the primary key.

like image 38
Paul Sanwald Avatar answered Oct 30 '22 10:10

Paul Sanwald


Using JPA you can do it this way.

CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaUpdate<User> criteria = builder.createCriteriaUpdate(User.class);
Root<User> root = criteria.from(User.class);
criteria.set(root.get("fname"), user.getName());
criteria.set(root.get("lname"), user.getlastName());
criteria.where(builder.equal(root.get("id"), user.getId()));
session.createQuery(criteria).executeUpdate();
like image 44
Arjun Nayak Avatar answered Oct 30 '22 10:10

Arjun Nayak


One more optimization here could be using dynamic-update set to true for the entity. This will make sure that whenever there is an update, only field(s) which are changed only gets updated.

like image 1
sudmong Avatar answered Oct 30 '22 08:10

sudmong