我如何有选择地使用Hibernate更新Spring bean的属性? [英] How do I selectively update properties on Spring beans with Hibernate?

查看:168
本文介绍了我如何有选择地使用Hibernate更新Spring bean的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个域对象:

  class MyPojo 
get / setA
get / setB
get / setC

如果我使用MyPojo作为表单的modelAttribute, :

 < form:form modelAttribute =myPojoaction =nextPagemethod =POST> 
< form:input path =a/>
< form:input path =b/>
< / form>

我有一个Controller方法:

  @RequestMapping(value = {/ nextPage},method = RequestMethod.POST)
public String theNextPageMethod(@ModelAttribute(myPojo)MyPojo myPojoObj){
//调用服务/ dao impl为了简洁省略
//但是dao impl却这样做:
sessionFactory.getCurrentSession()。saveOrUpdate(myPojoObj);





$ b

Spring / Hibernate使用属性a的表单输入值更新myPojoObj, b,但在我的情况下,它也将属性c的值设置为null。

这是预期的行为吗?如果是这样,保留分配给财产c的任何价值的最佳做法是什么?是否有注释或其他方法只更新属性a和b?



澄清:
理想情况下,我正在寻找可以在一页上更新a和b以及b和c 在另一个上,并保留所有其他属性为每个特定的请求静态。

解决方案

您想在哪里存储实体的状态? Session,view或db?

Add



@SessionAttributes({myPojo})



到您的控制器



或者在视图中使用隐藏的输入字段,c值

或使用@ModelAttribute注释控制器方法,并从db中返回实体每个请求



您也可以创建一个新的更小的POJO表单并使用Dozer将值复制到真实实体,并使用动态更新。


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:

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

And I have a Controller method like:

@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.

Is this the expected behavior? If so, what is the best practice to preserve any value assigned to property "c"? Is there an annotation or some other way to only update the properties "a" and "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.

解决方案

Where do you want to store the entity's state? Session, view or db?

Add

@SessionAttributes({"myPojo"})

To your controller

Or use a hidden input field in your view with c's value

Or annotate a controller method with @ModelAttribute and return the entity from the db each request

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.

这篇关于我如何有选择地使用Hibernate更新Spring bean的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆