0%

Entity Lifecycle

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
2
3
4
5
6
Session session = sessionFactory.openSession();
assertThat(getManagedEntities(session)).isEmpty();

List<FootballPlayer> players = s.createQuery("from FootballPlayer").getResultList();

assertThat(getManagedEntities(session)).size().isEqualTo(3);

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:

  1. The Session creates the entity is closed.
  2. Call Session.evict(entity) or Session.clear()
1
2
3
4
5
6
7
8
FootballPlayer cr7 = session.get(FootballPlayer.class, 1L);

assertThat(getManagedEntities(session)).size().isEqualTo(1);
assertThat(getManagedEntities(session).get(0).getId()).isEqualTo(cr7.getId());

session.evict(cr7);

assertThat(getManagedEntities(session)).size().isEqualTo(0);

But when Session.update() or Session.merge() called, the entity will be tracked by Persistence Context again.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
FootballPlayer messi = session.get(FootballPlayer.class, 2L);

session.evict(messi);
messi.setName("Leo Messi");
transaction.commit();

assertThat(getDirtyEntities()).isEmpty();

transaction = startTransaction(session);
session.update(messi);
transaction.commit();

assertThat(getDirtyEntities()).size().isEqualTo(1);
assertThat(getDirtyEntities().get(0).getName()).isEqualTo("Leo Messi");

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
FootballPlayer neymar = new FootballPlayer();
neymar.setName("Neymar");
session.save(neymar);

assertThat(getManagedEntities(session)).size().isEqualTo(1);
assertThat(neymar.getId()).isNotNull();

int count = queryCount("select count(*) from Football_Player where name='Neymar'");

assertThat(count).isEqualTo(0);

transaction.commit();
count = queryCount("select count(*) from Football_Player where name='Neymar'");

assertThat(count).isEqualTo(1);

Deleted Entity

Session.delete is called.

1
2
3
session.delete(neymar);

assertThat(getManagedEntities(session).get(0).getStatus()).isEqualTo(Status.DELETED);