简体   繁体   English

休眠多对一合并

[英]Hibernate many-to-one merge

I have a class Person with id, name, and status . 我有一个具有id,name和status的Person类。 the status is a class Status with id, and status string this is shortly the code generated by netbeans tool for hibernate status是带有ID的Status类,以及status字符串,这是netbeans工具为休眠生成的代码

class Person{
   long id;
   String name;
   Status status;
   //getters and setters
}
class Status{
   long id;
   String status;
   List<Person> persons;
   //getters and setters
}

the problem is when I want to merge a person in the session I get the status null 问题是当我想在会话中合并一个人时,状态为空

Person p = getById(1L); 人p = getById(1L); // person name=XX; //人名= XX; status=1 状态= 1

p.setName("YY"); p.setName(“ YY”);

session.merge(p); session.merge(p); // here the status is get NULL not-null property references a null or transient value: model.Status //这里的状态为get NULL not-null属性引用的是null或瞬态值:model.Status

I know that hibernate load the person object when merging so why the status return as null;?? 我知道休眠在合并时会加载人员对象,所以为什么状态返回为null?

In this case status is not null, but it's transient. 在这种情况下,状态不为null,而是瞬态的。 You're trying to merge Person before merging the Status that the person contains. 您正在尝试合并“ Person然后再合并该人员包含的“ Status ”。 So you're trying to introduce in the hibernate context an entity that has a reference outside the context. 因此,您尝试在休眠上下文中引入在上下文外部具有引用的实体。 The solution is either merging the status before merging the person or defining CascadeType.MERGE . 解决方案是在合并人员之前合并状态或定义CascadeType.MERGE

Lazy loading only works when the many-to-one reference is using the other object's primary key. 延迟加载仅在多对一引用正在使用另一个对象的主键时起作用。 And also be avoid of creating your architecture on one2many relations. 还要避免在一对多关系上创建体系结构。

Use like that in your person.hbm.xml file. 在person.hbm.xml文件中使用类似的内容。

<set name="status" table="status" 
            inverse="true" lazy="false" fetch="select">
        <key>
            <column name="id" not-null="true" />
        </key>
        <one-to-many class="xxx.Status" />
 </set>

and status.hbm.xml should be like that; 和status.hbm.xml应该是这样;

 <many-to-one name="person" class="xxx.Person" fetch="select">
      <column name="id" not-null="true" />
 </many-to-one>

i hope it helps. 我希望这会有所帮助。

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

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