Search code examples
javajpaentitymanager

JPA EntityManager caching


I have an entity defined as follows:

public class Version {
    @Id
    private Long id;
    private String content;
    @Transient
    private Model model;

    //...
}

From what I can see, when a find operation is done on Entity Manager, it makes a SELECT on the underlying database only once, and then the entity is cached in the Entity Manager. However, I see that if I assign a Model to the model property, this change is not reflected to the cached entity. E.g. if in one call, a find operation is done and Model is assigned, when I do find again from another EJB, model property is null again. Is this change not reflected to the cached entity? Perhaps because it's @Transient?


Solution

  • The entity manager maintains a first level cache, and this first level cache is thrown away as soon as the transaction has ended. Else, the cache would return stale values, since other transactions, in the same application or in another one, could modify or remove the cached entities.

    Moreover, concurrent transactions each have their own session-level cache, and thus their own instance of the same entity.

    If in a subsequent transaction, you find the same entity, a new SQL query will be issued, and a different instance of the entity will be returned.

    If something must be remembered across transactions for a given entity, then it should be made persistent in in the database. That's the point of a database.