Bart van Heukelom
Bart van Heukelom

Reputation: 44104

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?

Upvotes: 2

Views: 665

Answers (2)

Bart van Heukelom
Bart van Heukelom

Reputation: 44104

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.

Upvotes: 1

Michael De Keyser
Michael De Keyser

Reputation: 797

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.

Upvotes: 0

Related Questions