【问题标题】:Inserting the same object as property in Hibernate+Spring [duplicate]在Hibernate + Spring中插入与属性相同的对象[重复]
【发布时间】:2012-08-31 10:58:58
【问题描述】:

可能重复:
Spring + Hibernate : a different object with the same identifier value was already associated with the session

我有以下对象(简化)作为 JavaBean:

public class Person {
  private Integer id;
  private City cityOfBirth;
  private City city;
  // ...
}

在我的春季表格中,我有 2 个选择组合来选择两个城市,如下所示:

<form:form method="post" action="" commandName="person">
City of birth: <form:select path="cityOfBirth" items="${ cities }" itemValue="id" />
City: <form:select path="city" items="${ cities }" itemValue="id" />
...
</form:form>

我的 City 类的 PropertyEditor 将简单地调用我的 CityDao 的 get,如下:

@Component
public class CityDaoImpl implements CityDao {
  private @Autowired HibernateTemplate hibernateTemplate;

  public City get (Integer id) {
    return (City) hibernateTemplate.get(City.class, id);
  }
}

我的 PersonDao 会这样做以保存实例:

public void save (Person person) {
  hibernateTemplate.saveOrUpdate (person);
}

当我尝试用 2 个不同的城市保存一个人时,一切正常,但是当我选择同一个城市时,我收到以下错误:

org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.project.si.models.common.City#90]

我在其他帖子中读到,发生这种情况是因为 Hibernate Session 当前知道在 propertyEditor 调用 cityDao.get(id) 时获得的先前 City,所以我应该在某处使用 merge(),但我没有得到我应该在哪里应用这个..

【问题讨论】:

  • City 字段为什么有path="cityOfBirth"?那是错字吗?不应该是path="city"吗?
  • 你是正确的@limc,这是一个错字,我已经编辑了我的问题.. 谢谢

标签: spring hibernate spring-mvc


【解决方案1】:

问题是由于您将saveOrUpdate()操作从Person级联到City,当与要更新的对象具有相同ID的对象已经与@987654325关联时update()失败@。

我认为这个问题的最佳解决方案是从citycityOfBirth 中删除级联选项。

只要您的用户必须从现有城市列表中选择City,级联在这里就没有意义,因为您不需要将任何更改从Person 级联到City

您也可以使用merge() 代替saveOrUpdate()

public void save (Person person) {
    hibernateTemplate.merge(person); 
} 

【讨论】:

  • 删除级联选项可以完美解决我的问题,谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-03-31
  • 1970-01-01
  • 2012-11-09
  • 2021-10-30
  • 1970-01-01
  • 2019-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多