简体   繁体   中英

New entity with preset ID detected as “detached entity”

I have an entity Player with this ID defintion

@Id
@GeneratedValue
@Column(updatable=false)
private long id;

However, sometimes (but not always) I want to create a new instance with a preset ID.

player = new Player(...);
player.setId(externalId);
em.persist(player);

This apparently causes Hibernate to see it as a detached entity, throwing the exception

org.hibernate.PersistentObjectException: detached entity passed to persist

How can I avoid this?

I could remove the @GeneratedValue and generate IDs myself, something like:

begin transaction
if id not preset {
    do {
        id = random number
    } while (id in use)
}
create player with id
commit transaction

That should be safe, with the transaction, but it's less optimal than letting the database deal with it.

There is something wrong there. Could you please tell us why you want a fixed Id ? Because you're actually saying "please create an ID for me I NEVER want to deal with this" then you are sometimes trying to set an ID yourself which probably means you are corrupting the whole thing.

That exception might be because you are setting an ID that is already used. Then when trying to persist, hibernate detects it as out of sync (detached) with what's in DB so he just throws that exception.

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