Java – JPA and first level cache, what’s the point?

Entitymanager maintains the first level cache for retrieved objects, but if you want to have a thread safe application, you need to create and close entitymanager for each transaction

So, if these entities are created and closed for each transaction, what is the focus of level 1 caching? Or, if you work in a single thread, is the entitymanager cache available?

Solution

The first level cache is used for other purposes It is basically the context in which JPA places entities retrieved from the database

performance

Therefore, to begin with the obvious, it can avoid having to retrieve records during transaction processing, and use some form of cache when improving performance In addition, delayed loading is considered How to implement it without caching to record entities that have been loaded late?

Cyclic relationship

This caching purpose is critical to the implementation of an appropriate ORM framework In object - oriented languages, object graphs usually have circular relationships For example, a department with an employee object and an employee object belongs to department

Without context (also known as unit of work), it is difficult to track records that you already have ormed, and new objects will eventually be created. In this case, you may even fall into an infinite loop

Tracking changes: commit and rollback

In addition, this context tracks your changes to objects so that they can be retained or rolled back later at the end of the transaction Without such a cache, you will be forced to immediately refresh the changes to the database when they occur, and then you cannot roll them back or optimize the best time to refresh them to the store

Object identity

Object identification is also very important in ORM framework That is, if you retrieve employee ID 123, if you need the employee at some time, you should always get the same object instead of a new object containing the same data

This type of cache is not shared by multiple threads. If so, you will sacrifice performance and force everyone to pay a price, even if they can use a single threaded solution Except you'll end up with a more complex solution, like killing flies with a bazooka

That's why if you need a shared cache, you actually need a L2 cache and an implementation

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>