Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 839
Ariod Avatar asked Oct 20 '25 10:10

Ariod


1 Answers

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.

like image 118
JB Nizet Avatar answered Oct 22 '25 23:10

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!