简体   繁体   中英

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 is a complex class which stores a hierarchy of other objects that also have generated Ids.

I can query a json web service to get an instance of Player. The json gets parsed by Jackson, which builds a full Player object, except it won't have any of the generated Ids. I essentially want to do a saveOrUpdate on this instance of player.

One option would be query the database for a Player object by natural id. 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. 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. Unfortunately I haven't been able to make this work. I thought using merge() would do the trick, but I get this exception:

org.hibernate.HibernateException: More than one row with the given identifier was found

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? If you did that, you could saveOrUpdate to persist the Player object.

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.

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.

br, Jens

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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