简体   繁体   中英

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?

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.

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();

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM