简体   繁体   English

如何使用Hibernate有选择地更新Spring bean的属性?

[英]How do I selectively update properties on Spring beans with Hibernate?

Given a domain object like: 给定一个域对象,例如:

class MyPojo
  get/setA
  get/setB
  get/setC

If I use MyPojo as the modelAttribute for a form, that has something like: 如果我将MyPojo用作表单的modelAttribute,则其内容类似于:

 <form:form modelAttribute="myPojo" action="nextPage" method="POST">
    <form:input path="a"/>
    <form:input path="b"/>
 </form> 

And I have a Controller method like: 我有一个Controller方法,例如:

@RequestMapping(value = {"/nextPage"}, method = RequestMethod.POST)
public String theNextPageMethod(@ModelAttribute("myPojo") MyPojo myPojoObj) {
         //call to a service/dao impl are omitted for brevity
         //but the dao impl does:
        sessionFactory.getCurrentSession().saveOrUpdate(myPojoObj);
}

Spring/Hibernate updates myPojoObj with the form input values for properties "a" and "b" but in my case, it's also setting the value of property "c" to null. Spring / Hibernate使用属性“ a”和“ b”的形式输入值更新myPojoObj,但在我的情况下,它还将属性“ c”的值设置为null。

Is this the expected behavior? 这是预期的行为吗? If so, what is the best practice to preserve any value assigned to property "c"? 如果是这样,保留分配给属性“ c”的任何值的最佳实践是什么? Is there an annotation or some other way to only update the properties "a" and "b"? 是否有注释或其他方式仅更新属性“ a”和“ b”?

CLARIFICATION: Ideally, I'm looking for something to allow for updating "a" and "b" on one page and "b" and "c" on another and keep all the other properties static for each particular request. 澄清:理想情况下,我正在寻找可以在一个页面上更新“ a”和“ b”,而在另一页面上更新“ b”和“ c”的东西,并针对每个特定请求使所有其他属性保持不变。

Try Dynamic-Update Attribute it should solve your problem. 试试动态更新属性,它应该可以解决您的问题。

@DynamicUpdate

Now only changed columns will be update. 现在,仅更改的列将被更新。 See also example http://www.mkyong.com/hibernate/hibernate-dynamic-update-attribute-example/ 另请参见示例http://www.mkyong.com/hibernate/hibernate-dynamic-update-attribute-example/

Where do you want to store the entity's state? 您想在哪里存储实体的状态? Session, view or db? 会话,视图还是数据库?

Add

@SessionAttributes({"myPojo"}) @SessionAttributes({ “myPojo”})

To your controller 给你的控制器

Or use a hidden input field in your view with c's value 或使用c的值在视图中使用隐藏的输入字段

Or annotate a controller method with @ModelAttribute and return the entity from the db each request 或使用@ModelAttribute注释控制器方法,并从db每个请求返回实体

You can also create a new, smaller POJO just for the form(s) and use Dozer to copy values to/from your real entity, and use dynamic update. 您也可以只为表单创建一个新的较小的POJO,并使用Dozer将值复制到实际实体中或从中复制值,并使用动态更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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