I have a question about entity states in JPA.
I’ve read some article about entity states in jpa and my understanding about them is that:
- a transient object is a newly created object that hasn’t been associated with Persistence Context and does not represent a record in database.
and
- when we remove an object, it doesn’t have any association with Persistence Context anymore and its record in database will be removed.
now my question is; both of those states (transient
and removed
) does not have any association with Persistence Context and also they do not represent any record in database (they do not have any record in database). so both of them are same. then what is the difference between these two?
Edit:
can we say that at the end, the transient
object does not have an id but the removed
object has an id?
Advertisement
Answer
Technically they are not the same, although that they may appear to be seen as to have the same behaviour at times, but they are used to represent specific life cycle stage for an object.
Transient
should be considered during the initial state for an object when the object is created using the keywords new
, these objects are then only considered to be existing in memory and will be garbage collected as soon as all references of them is gone. But since the Transient
state is the start of an object’s lifecycyle, it may later be put forward into a managed state and eventually be permanently stored in the database.
Removed
state is the last possible state for an object usually when it has been manually staged for physical deletion from the underlying database during commit, i.e. the this state is usually reachable for an object that is already stored in the db, but is now longer needed.
So yes, when you look at them in isolation
, close to the end of each of these two life cycle events once their effect takes in place, they may look the same, i.e. end of a transient
state of which the object may not have been moved into an managed state after the last reference is removed, nothing is left, hence no records.
The end of removed
state of which an object has been physically deleted from the database where it once exists, nothing left, hence no record again.