Understanding the first level JPA cache

I can bet that every Java developer at least heard about L1 (aka EntityManager or Session) cache. But is your level of understanding it good enough? If you're not sure, consider going through this post.

At first, we need to know what the persistence context is. Following EntityManager JavaDoc we know, that:
"A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed." 
In fact, the first level cache is the same as the persistence context. That means operations such as persist(), merge(), remove() are changing only internal collections in the context and are not synchronized to the underlying database. What is the mosts important here is what happens when you invoke the clear() method. It clears the L1 cache. But we know L1 == persistence context. Does it mean clearing L1 removes all entities? In fact yes - all entities will be dropped and never synchronized to the database. That's not a secret, it states in the documentation - "Unflushed changes made to the entity (...) will not be synchronized to the database." But who cares about the docs? :)

So how does it look in practice? Take a look at the code below:

em.persist(myEntity); // saves entity to the context
em.flush(); // triggers insert into database
em.clear(); // removes entity from the context == entity is no longer managed

If you omit flush() the entity won't hit the database. It will live only in your code, and after leaving method which created this object will be lost. Let's take a look at the next sample:

myEntity.setName("old name");
em.persist(myEntity);
em.flush();
em.clear();
myEntity.setName("new name");
em.flush();

What will be the value of the name property after finishing this code? Of course still "old name", because in the moment when setName() has been invoked the entity is no longer managed and it has to be merged with the persistent context (by invoking em.merge(myEntity) method) to be the subject of the dirty checking.

But I'm not calling flush() method in my code and everything works!? But do you call clear()? That's what I thought. What is the default flush behavior? JPA by default flushes changes on commit as well as every query execution (FlushModeType.AUTO). If you change it to COMMIT (with em.setFlushMode(FlushModeType.COMMIT) method) then flush will occur (as name suggests) only on commit.

Deep understanding of the L1 behavior is especially important when dealing with batch operations. Why? If you want such operation to be effective, we must manually flush changes from time to time (let's say every 100 operations). Do you know, that flush() doesn't clear the persistence context? So what? Flush is not cheap because it must process all entities in the context to see if there is anything to synchronize with the database. If you won't clear the context manually immediately after flush(), every next operation will take longer and longer. To be honest this time grows exponentially, which seems to be sufficient reason to remember about mentioned technique.

If you're interested in deeper dive into persistence context please feel free to clone and play with this repository, which contains all described cases and examples.

Comments

MOUNIKA said…
Greetings! Very helpful advice within this article! It’s the little changes that produce the biggest changes. Thanks for sharing!
Abinitio Online Training Instittue
Microsoft Azure Online Training Instittue
App V Online Training Instittue
Surya said…
This comment has been removed by the author.
This comment has been removed by the author.
Raja said…
I recently had the good fortune of reading your articles. It was well-written. In fact, I have already benefited from your discussion before. I look forward to reading your next informative work. Thank you.

Best Air hostess Training Institute in Chennai
Best Ground staff Training institute in Chennai
Best Ground staff Academy in Chennai


vivikhapnoi said…
Fantastic!! you are doing good job! I impressed. Many bodies are follow to you and try to some new.. After read your comments I feel; Its very interesting and every guys sahre with you own works. Great!!
vé máy bay đi seoul

mua vé máy bay đi nhật bản

vé máy bay giá rẻ từ việt nam đi nhật

giá vé máy bay đi đài loan

vé máy bay sài gòn đài bắc

vietjet bay cao hùng
You have worked nicely with your insights that makes our work easy. The information you have provided is really factual and significant for us. Keep sharing these types of article, Thank you.Miami website designer
Radhapraveen said…
Fantastic to read this blog. Thanks you so much for sharing this kind of article.
Python Classes in Chennai
Python Classes Near Me
Best Python Training in Bangalore
Thanks for the interesting blog that you have implemented here. Very helpful and innovative. Waiting for your next upcoming article.

escort service in Noida
Riya_roy said…
The Blog Your Shared is Very Helpful, This is So good hope we get More blogs on your site like this, This blog is so infomative and exited for your next blog

Escorts Service in Mahipalpur.
Rashi Singh said…
The Blog Your Shared is Very Helpful, This is So good hope we get More blogs on your site like this, This blog is so informative and exited for your next blog
Escorts Service In Mathura
Meerut Escorts
Noida Escorts Service
Varanasi Escort Service
Allahabad Call Girls
hema said…
This post is so interactive and informative.keep updating more information...
ETL tools
Python
Nikhil N said…
valuable blog,Informative content...thanks for sharing, Waiting for the next update…
What is google flutter?
Benefits of Flutter
rinjuesther said…
valuable blog,Informative content...thanks for sharing, Waiting for the next update...
Basics of Protocol Testing
What is Protocol Testing?
abiroymathew said…
I read this blog, a Nice article...Thanks for sharing and waiting for the next...
Software Testing Course in Bangalore
Best Software Testing Institute in Bangalore
Prime Bit said…
Thanks for sharing such a informative blog. I would like to share with my students who are taking protocol testing training and 5g protocol testing courses.
Amy Lewis said…
Thanks for sharing useful inomation.

Why Choose QuikieApps, for your Video Analytics Solutions?
Healthandfigure said…
hello dosto ye information bahut important hai aapke life ke lia . ajj kal logo ke life me sextual life bahut khrab chalti hai wo log apne partner ko khus nahi kar pate hai
kaamshakti badhane ki aayurvedik dawa patanjali
agar aap vi aise problem ko face karrhe ho to ye article bahut jaruri hai

Popular posts from this blog

Overview of the circuit breaker in Hystrix

Understanding Spring Web Initialization

Do we really still need a 32-bit JVM?