Home > other >  Is a transient entity with id set still a transient entity or a detached entity
Is a transient entity with id set still a transient entity or a detached entity

Time:04-17

By definition, a newly instantiated POJO, say transientPerson, is a transient entity.

Person transientPerson = new Person();

An entity detached from persistent context is a detached entity.

Person detachedPerson = session.get(Person.class, id);
session.detach(detachedPerson);

After setting all the fields of detachedPerson into transientPerson, is transientPerson still a transient entity?

transientPerson.setId(detachedPerson.getId());
transientPerson.setName(detachedPerson.getName());

If this is the case, does it mean that I'm able to use persist(transientPerson) to update the corresponding table in DB?

CodePudding user response:

The main difference between transient and detached entity is whether that entity really has the corresponding record exist in DB. Transient entity does not have but detached entity has (See the official definition at there).

So in this case, transientPerson technically will become detached as there are really a DB record exist for it.

And calling persist() on the entity that already exists in the DB (i.e detached entity) will throw EntityExistsException. You have to use merge() to insert or update the detached instead.

  • Related