Posts

Showing posts with the label jpa

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 al...

JPA in case of asynchronous processing

Few years ago in Java world it was almost obvious that every "enterprise" class project needed JPA to communicate with database. JPA is a perfect example of " leaky abstraction " described by Joel Spolsky. Great and easy at the beginning but hard to tune and limiting at the end. Hacking and working directly with caches, flushes and native queries is a daily routine for many backend developers involved in data access layer. There are enough problems and workarounds to write a dedicated book "JPA for hackers", but in this article I'll focus only on concurrent entity processing. Let's assume the situation: we have Person entity which in some business process is updated by some service. @Entity public class Person { @Id @GeneratedValue private Long id; private String uuid = UUID.randomUUID().toString(); private String firstName; private String lastName; // getters and setters } To ignore any domain complexity w...