0

Let's say I want to delete my entity A with a ManyToOne relation to entity B. After deleting entity A, if that was the last entity related to entity B, I also want to delete entity B within the same transaction. My implementation for these actions looks like the following:

@Transactional    
fun delete(idEntityA: Long, idEntityB: Long) {
        entityARepository.deleteById(idEntityA)
        if (entityARepository.countDistinctByEntityBId(idEntityB) == 0L) {
            entityBRepository.deleteById(idEntityB)
        }
    }

According to my understanding of how Spring Data JPA(/Hibernate) works, the count operation should not take into account the preceding delete operation, as it has not been committed yet. Although if I execute the method, it already takes into account the uncommitted delete operation of entity A. My question now, as I can't find proper documentation: Does Spring Data JPA or Hibernate also take into account uncommitted operations from the same transaction when reading data from the database?

I know that if I would execute the count query in a different transaction with the default isolation mode, it would not know about the delete operation if the respective transaction would not be committed yet.

Thanks in advance!

iamroot
  • 33
  • 2

1 Answers1

1

JPA implementations by default flush changes to the databases before executing a query. Therefore the count will consider the previous delete.

If you change the flush mode it still MIGHT perform the delete in the database again resulting in the count observing the delete.

This is pretty much independent from Spring Data JPA which sits on top of JPA (see Spring Data JDBC / Spring Data JPA vs Hibernate).

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
  • Thanks for the clarification! This post also helped me understand it better: https://stackoverflow.com/questions/56812221/jpa-auto-flush-before-any-query – iamroot Feb 04 '21 at 07:54