views:

65

answers:

1

How can I update an entity "effectively" in hibernate just as by using SQL.

For example : I have a Product entity, which has a field name createTime. When I use session.saveOrUpdate(product) I have to get this field from database and then set to product then update, actually whenever I use session.saveOrUpdate(), I updated ALL fields, even if I need to update only one field. But most of time the value object we passed to DAO layer can't contain all fields information, like the createDate in Product, we seldom need to update this field.

How to just update selected fields? Of course I can use HQL, but that will separate save and update logic .

It would be better If Hibernate has a method like this :

session.updateOnlyNotNullFields(product);

How can I do this in Hibernate ?

+4  A: 

By default, Hibernate doesn't use dynamic updates and indeed updates the whole object. The resulting overhead is IMO minimal even for large entities and you shouldn't worry about it.

It is possible to change this behavior though by setting the dynamic-update attribute to true on the class element:

dynamic-update (optional - defaults to false): specifies that UPDATE SQL should be generated at runtime and can contain only those columns whose values have changed.

And this is the annotation equivalent (on @org.hibernate.annotations.Entity, it's an extension to JPA):

dynamicUpdate: allow dynamic SQL for updates

But I think you're worrying too much. Use the above in exceptional and very particular circumstances only.

Pascal Thivent
Thanks for the revision , I not an English speaker. I am not worrying the overhead , what I am worrying is the front end value object doesn't contains full properties of the entity , and update using this kind of transient object , will set existing fields to null .
ZZcat
@Tony Ohhh, I understand now. Not sure this is the right answer though.
Pascal Thivent
@Pascal Thivent: If You have the right answers , please let me know :)
ZZcat
@Tony Well, why don't you send and return fully valued VO? Why are fields null?
Pascal Thivent
@Pascal Thivent: Fully valued VO is not really necessary , e.g. I only allow the user to update 7 of 12 properties , it's all right to get all of the properites from datebase , but I have to store the other 5 properties somewhere in the front end , in order to passback a full valued VO ? And often some of the properties should be updated on a very rarely basis , i.e. createTime .
ZZcat
@Pascal Thivent:And for some security issues , we often get the projections of the entity , don't allow some fields to be fetched out by the user, these fields often created in the server side in the saving process initialized only once ,so we can't use hibernate saveOrUpdate().
ZZcat
@Tony Not easy to discuss in this little 600 char box :) Actually, what I don't get after reflexion is: why would using VOs set some existing fields on an entity to `null` (your initial comment)?
Pascal Thivent