简体   繁体   English

无需主键即可休眠保存或更新对象

[英]hibernate save or update object without primary key

Say I have a class called Player, which is persisted with hibernate, and has both a generated ID and a composite natural id. 假设我有一个名为Player的类,该类与hibernate保持一致,并且具有生成的ID和复合的自然ID。 Player is a complex class which stores a hierarchy of other objects that also have generated Ids. Player是一个复杂的类,用于存储也已生成ID的其他对象的层次结构。

I can query a json web service to get an instance of Player. 我可以查询json网络服务以获取Player的实例。 The json gets parsed by Jackson, which builds a full Player object, except it won't have any of the generated Ids. 杰克逊(Jackson)对json进行了解析,杰克逊(Jackson)构建了一个完整的Player对象,但它不会包含任何生成的ID。 I essentially want to do a saveOrUpdate on this instance of player. 我本质上想在此播放器实例上执行saveOrUpdate。

One option would be query the database for a Player object by natural id. 一种选择是通过自然ID在数据库中查询Player对象。 If no object is returned, do a save. 如果没有返回对象,请保存。 Otherwise, manually copy all the values of the Player object (and all it's fields) from the web service to the object from the database, then do an update. 否则,请手动将Web服务中Player对象的所有值(及其所有字段)复制到数据库中的对象,然后进行更新。 I don't like this option since it seems inefficient and would include a lot of extra code. 我不喜欢此选项,因为它似乎效率低下,并且会包含很多额外的代码。

What I would prefer to do is just copy the generated Ids from the database object to the object from the web service, then do an update on that. 我想做的只是将生成的ID从数据库对象复制到Web服务的对象,然后对此进行更新。 Unfortunately I haven't been able to make this work. 不幸的是,我无法完成这项工作。 I thought using merge() would do the trick, but I get this exception: 我以为可以使用merge()来解决问题,但是我得到了这个异常:

org.hibernate.HibernateException: More than one row with the given identifier was found org.hibernate.HibernateException:找到多个具有给定标识符的行

What's the best way to handle this scenario? 处理这种情况的最佳方法是什么?

May I asked why you don't let Jackson pass the generated Id (which I assume is the PK) to the client? 请问您为什么不让杰克逊将生成的ID(我认为是PK)传递给客户端? If you did that, you could saveOrUpdate to persist the Player object. 如果这样做,则可以保存或更新以持久保存Player对象。

I handle relations to other objects (Entities and Collections that are not supposed to be handled by the same method) by making sure Jackson almost only uses the PK (actually PK and name, so links can be created) when de/serializing, using @JsonSerialize. 我通过确保杰克逊在反序列化/序列化时几乎只使用PK(实际上是PK和名称,因此可以创建链接),使用@来处理与其他对象(不应使用相同方法处理的实体和集合)之间的关系。 JsonSerialize。

That works swell with Hibernate - even though my Entity refers to other Entities/Collections, I can simple do CRUD operations using no DTOs, conversion or extra db access. 这与Hibernate兼容-即使我的实体引用了其他实体/集合,我也可以简单地执行CRUD操作,而无需DTO,转换或额外的数据库访问。

br, Jens br,詹斯

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

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