开发者

Effective Entity Update In Hibernate?

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 ?


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.


If you use the latest hibernate(3.5.5),you can native sql as following,

session.createSQLQuery("update table_name set column_1=:col1 ").executeUpdate(). this way don't load or get first and then update.just update as using sql.Hope help you!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜