Background
Persistence Context
Persistence Context is the middle layer between Database with Business Code. It’s a staging area for:
- Convert the Database Row to Entity.
- Ready for the Client to read Entity.
- The alerted Entity by business code.
Lifecycle
Managed Entity
A managed entity is a representation of a database table row.
1 | Session session = sessionFactory.openSession(); |
Detached Entity
A detached entity is a Entity POJO corresponds to a decision table row, but not tracked by the Persistence Context.
A managed entity can converted into detached entity by below ways:
- The Session creates the entity is closed.
- Call Session.evict(entity) or Session.clear()
1 | FootballPlayer cr7 = session.get(FootballPlayer.class, 1L); |
But when Session.update()
or Session.merge()
called, the entity will be tracked by Persistence Context again.
1 | FootballPlayer messi = session.get(FootballPlayer.class, 2L); |
Transient entity
A entity POJO that not exist in the Persistent Context store and not managed.
A typical example is to create a instance by constructor.
To make a transient entity persistent, we need to call Session.save(entity)
or Session.saveOrUpdate(entity)
:
1 | FootballPlayer neymar = new FootballPlayer(); |
Deleted Entity
Session.delete
is called.
1 | session.delete(neymar); |