How do I update a certain field of a Model in Playframework?

一世执手 提交于 2019-12-08 12:46:25

问题


Suppose we have a User class, if I want to update it's name:

User user = User.findById(123); user.name = "someone"; user.save();

The generated SQL would be

update user as user0 set user0.name = ? user0.email = ? .....

That means Play didn't realize I just want to update a single field. Is there any way could make the generated SQL only update the specified fields ?


回答1:


Info: this is answer for Play 2 + Ebean! so it DOES NOT work with Play 1 + JPA

There are some options in Ebean's API, so you should check it and choose one:

  • Update<T> - check in the sample for @NamedUpdates annotation
  • Ebean.createUpdate(beanType, updStatement)
  • SqlUpdate - you can just perform raw SQL update, without need for giving the entity type



回答2:


This is dependent on whether Play (or actually Avaje Ebean) actually tracks which of the fields are changed. It's simpler to update all of the fields instead.

This isn't an issue performance-wise either, so I wouldn't waste too much time looking for a solution.




回答3:


You can use hibernate's dynamic update feature : http://www.mkyong.com/hibernate/hibernate-dynamic-update-attribute-example/

But remember that this have negative impact on performance as database cannot cache statements. See here for others explanations : Hibernate : dynamic-update dynamic-insert - Performance Effects



来源:https://stackoverflow.com/questions/17439364/how-do-i-update-a-certain-field-of-a-model-in-playframework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!