Spring read-only transaction Hibernate optimization

(Last Updated On: September 25, 2018)


In this article, I’m going to explain how the Spring read-only transaction Hibernate optimization works.

After taking a look at what the Spring framework does when enabling the readOnly attribute on the @Transactional annotation, I realized that only the Hibernate flush mode is set to FlushType.MANUAL without propagating the read-only flag further to the Hibernate Session.

So, in the true spirit of open-source software developer, I decided it’s time to make a change.

Entity loaded state

When loading an entity, Hibernate extracts the loaded state from the underlying JDBC ResultSet. This process is called hydration on Hibernate terminology and is done by the org.hibernate.persister.entity.EntityPersister like this:

final Object[] values = persister.hydrate(

The loaded state or hydrated state is needed by dirty checking mechanism to compare the current entity state with the loaded-time snapshot and determine if an UPDATE statement is needed to be executed at flush-time. Also, the detached state is used by the versionless optimistic locking mechanism to build the WHERE clause filtering predicates.

Therefore, upon loading an entity, the detached state is stored by the Hibernate Session unless the entity is loaded in read-only mode.

Read-only entities

By default, entities are loaded in read-write mode, meaning that the detached state is kept by the current Persistence Context until the entity is detached or if the JPA EntityManager or Hibernate Session is closed.

In order to load entities is the read-only mode, you can set either set the defaultReadOnly flag at the Session level or set the org.hibernate.readOnly JPA query hint.

To set the read-only for all entities loaded by a Hibernate Session either through a query or via direct fetching, you need to enable the defaultReadOnly property like this:

Session session = entityManager.unwrap(Session.class);

Or, if you have a default read-write Session and only want to load entities in read-only mode for a particular query, you can use the org.hibernate.readOnly JPA query hint as follows:

List<Post> posts = entityManager
    "select p from Post p", Post.class)
.setHint(QueryHints.HINT_READONLY, true)

Spring @Transactional annotation

Spring, just like Java EE, offers support for declarative transactions. Therefore, you can use the @Transactional annotation to mark the service layer method that should be wrapped in a transactional context.

The @Transactional annotation offers the readOnly attribute, which is false by default. The readOnly attribute can further be used by Spring to optimize the underlying data access layer operations.

Prior to Spring 5.1, when using Hibernate, the readOnly attribute of the @Transactional annotation was only setting the current Session flush mode to FlushType.MANUAL, therefore disabling the automatic dirty checking mechanism.

However, because the readOnly attribute did not propagate to the underlying Hibernate Session, I decided to create the SPR-16956 issue and provided a Pull Request as well, which after being Jürgenized, it got integrated, and available starting with Spring Framework 5.1.

Testing time

Let’s consider we have the following service and data access layer classes in our application:

Forum service and data access layer classes

The PostDAOImpl class is implemented like this:

public class PostDAOImpl 
        extends GenericDAOImpl<Post, Long> 
        implements PostDAO {

    protected PostDAOImpl() {

    public List<Post> findByTitle(String title) {
        return getEntityManager()
            "select p " +
            "from Post p " +
            "where p.title = :title", Post.class)
        .setParameter("title", title)

While the ForumServiceImpl looks as follows:

public class ForumServiceImpl implements ForumService {

    private PostDAO postDAO;

    private TagDAO tagDAO;

    private EntityManager entityManager;

    public Post newPost(String title, String... tags) {
        Post post = new Post();
        return postDAO.persist(post);

    @Transactional(readOnly = true)
    public List<Post> findAllByTitle(String title) {
        List<Post> posts = postDAO.findByTitle(title);

        org.hibernate.engine.spi.PersistenceContext persistenceContext = getHibernatePersistenceContext();

        for(Post post : posts) {

            EntityEntry entityEntry = persistenceContext.getEntry(post);

        return posts;

    public Post findById(Long id) {
        Post post = postDAO.findById(id);

        org.hibernate.engine.spi.PersistenceContext persistenceContext = getHibernatePersistenceContext();

        EntityEntry entityEntry = persistenceContext.getEntry(post);

        return post;

    private org.hibernate.engine.spi.PersistenceContext getHibernatePersistenceContext() {
        SharedSessionContractImplementor session = entityManager.unwrap(
        return session.getPersistenceContext();

We are interested in the findAllByTitle and findById service methods.

Notice that the findAllByTitle method is annotated with @Transactional(readOnly = true). When loading the Post entities matching the given title, Hibernate is going to fetch the entities in read-only mode, therefore discarding the loaded state, which we can validate via the org.hibernate.engine.spi.PersistenceContext.

On the other hand, the findById method uses the default read-write @Transactional annotation, and we can see that the org.hibernate.engine.spi.PersistenceContext contains the detached state of the currently fetched Post entity.

When running the test that proves this new Spring 5.1 Hibernate optimization, everything works as expected:

public void test() {
    Post newPost = forumService.newPost(
        "High-Performance Java Persistence", 

    List<Post> posts = forumService.findAllByTitle(
        "High-Performance Java Persistence"
    assertEquals(1, posts.size());

    Post post = forumService.findById(newPost.getId());
        "High-Performance Java Persistence", 

Cool, right?

If you enjoyed this article, I bet you are going to love my Book and Video Courses as well.


The main advantage of the Spring 5.1 read-only optimization for Hibernate is that we can save a lot of memory when loading read-only entities since the loaded state is discarded right away, and not kept for the whole duration of the currently running Persistence Context.

Subscribe to our Newsletter

* indicates required
10 000 readers have found this blog worth following!

If you subscribe to my newsletter, you'll get:
  • A free sample of my Video Course about running Integration tests at warp-speed using Docker and tmpfs
  • 3 chapters from my book, High-Performance Java Persistence, 
  • a 10% discount coupon for my book. 
Get the most out of your persistence layer!


14 thoughts on “Spring read-only transaction Hibernate optimization

  1. Thanks for this post, excellent as usual.

    I have one more question, what’s the impact in projection queries and DTO results?

    1. Thanks. There’s no impact for projection queries or DTO results since only entities retain their detached state.

  2. Nice article!

    I can’t though understand the difference between a method annotated with a read-only @Transactional and another method where the annotation is missing.

    For example, what is the difference between:

    @Transactional(readOnly = true)
    public List findAllByTitle(String title) {


    public List findAllByTitle(String title) {


  3. How does it work if one Spring bean annotated with @Transactional(readOnly = true) call another with @Transactional(readOnly = false)? Will the session be read only or not? And what about the opposite case, where readOnly=false calls readOnly=true?

    Thanks in advance!

    1. The behaviour is given by the transaction propagation rules. Once the transaction context is set, you can’t change it.

  4. Hi and thanks for your great article (and for the many others!).

    There’s one thing though I’d like to have some more clarifications on a Java EE perspective.

    I’m already using the the “org.hibernate.readOnly” flag to disable dirty checking like mentioned in your post. I’m not though relying on the “org.hibernate.flushMode” hint.

    Would I gain some further more optimization by providing FlushMode.MANUAL hint in a situation when I know in advance, that, within my transaction, all entities will/should be fetch using the readOnly flag?


  5. I wonder what happens when we load same entity in both modes (using query hint) – does Hibernate try to keep them consistent?

      1. So I the read-only read is first then hibernate will keep the object in session? What if I read in read-write mode later? Were will it take the hydrated state for dirty checking from?

      2. I don’t think so. The entity should be in RO mode until you detach it or you clear the Session. But, you can clone my high-performance-java-persistence GitHub repository and try this use case and see how it works. That’s the beauty of open-source software.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.