NaturalId,它是如何工作的?
我的 nativeid 有问题,我不知道我做得是否正确。
我有一个名为 Aircraft 的类,它有一个生成的 id。但它的本机 id 是序列号(整数)和模型(自定义类),如下所示:
public class Aircraft{
@Id @GeneratedValue(strategy=GenerationType.AUTO,generator="COD_NS_AENV")
@Column(name="COD_NS")
private Integer id;
@Column(name="NUM_IDENT_NS_AENV")
@NaturalId
private Integer serialNumber;
@ManyToOne
@NaturalId
private Model model;
.
.
.
}
我从 XML 加载此类并保存到数据库中,如下所示:
.
.
.
Aircraft aircraft= (Aircraft)xstream.fromXML(reader);
Session session = HibernateUtil.openSession();
Transaction t = session.beginTransaction();
session.saveOrUpdate(aircraft.getModelo());
session.saveOrUpdate(aircraft);
t.commit();
session.close();
它对于插入工作正常,但我的问题是当我执行时这段代码再次使用相同的信息,Hibernate 插入另一架飞机。我希望 Hibernate 只更新当前注册表。
我重写了 equals() 方法来测试 serialNumber 和 Model 属性,但它从未被调用。
我不知道如何让 Hibernate 理解带有serialNumber 和model 的对象是NativeId。
提前致谢!
亚历山大
I´m having a problem with nativeid and i don´t know if i am doing right.
I have a class called Aircraft that has an generated id. But its native id is the serial number(Integer) and Model( a custom class) like below:
public class Aircraft{
@Id @GeneratedValue(strategy=GenerationType.AUTO,generator="COD_NS_AENV")
@Column(name="COD_NS")
private Integer id;
@Column(name="NUM_IDENT_NS_AENV")
@NaturalId
private Integer serialNumber;
@ManyToOne
@NaturalId
private Model model;
.
.
.
}
I load this class from an XML and save into the database, like this:
.
.
.
Aircraft aircraft= (Aircraft)xstream.fromXML(reader);
Session session = HibernateUtil.openSession();
Transaction t = session.beginTransaction();
session.saveOrUpdate(aircraft.getModelo());
session.saveOrUpdate(aircraft);
t.commit();
session.close();
It works fine for insert,but my problem is when I execute this code again with the same information, Hibernate inserts another aircraft. I want that Hibernate only updates the current registry.
I overrided the method equals() to test the serialNumber and Model attributes but it is never called.
I don´t know how to make Hibernate understand that an object with serialNumber and model are the NativeId.
Thanks in advance!
Alexandre
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最有可能的是,Hibernate 只是使用
@Id
属性并每次生成新值。我认为,发生这种情况是因为您从 XML 读取对象,而 id 不在 XML 中。我认为自然 ID 不会与代理自动生成的 ID 很好地共存。对于saveOrUpdate
Hibernate 将仅查看id
来确定对象是否是新的。以下是有关 Hibernate 论坛 的更多详细信息。
Most likely Hibernate just uses
@Id
property and generates new value every time. That happens because you read your object from XML and id is not in XML, I assume. I don't think natural id will coexist well with surrogate autogenerated id. And forsaveOrUpdate
Hibernate will just look atid
to determine if object is new.Here is more details on Hibernate forums.