Govinda Sakhare
Govinda Sakhare

Reputation: 5749

Unable to read uncommited data using Spring JPA READ_UNCOMMITTED isolation level

I have two JPA repository methods, one method updates the record and goes for I/O operation. Another method reads a record from the Postgres database, but here I want to allow dirty read.

The below code is experimental, not production-grade one.

Controller endpoints to trigger JPA repository methods:

@GetMapping( "update" )
public String updatePerson( ) throws InterruptedException {
    return managerService.updatePerson();
}

@GetMapping( "read_uncommitted" )
public String getUncommited( ) {
    return personService.readUncommited();
}

JPA Repository methods:

@Transactional(propagation = Propagation.REQUIRES_NEW)
public String updatePerson( ) throws InterruptedException {
    Person person = entityManager.find(Person.class, 55L);
    person.setName("Chuck Norris");
    entityManager.persist(person);
    entityManager.flush();
    Thread.sleep(15000); // imitating I/O behaviour
    return person.getName();
}

@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true, isolation = Isolation.READ_UNCOMMITTED )
public String readUncommited() {
    Person person = entityManager.find(Person.class, 55L);
    return person.getName();
}

In updatePerson() I am updating person object, flushing the record, I believe transaction will be committed once method call completes i.e. record will remain in uncommitted state due Thread.sleep

Now in readUncommitted() I am trying to read the same record just a moment after triggering the updatePerson(). The method is annotated with Isolation.READ_UNCOMMITTED, but I am unable to read the above updated-uncommitted record.

Upvotes: 1

Views: 1071

Answers (1)

Laurenz Albe
Laurenz Albe

Reputation: 246513

The SQL standard defines READ UNCOMMITTED by not defining any isolation guarantees for it. In other words, it does not require that you actually get to see uncommitted data in that isolation level.

PostgreSQL takes advantage of that by accepting READ UNCOMMITTED, but actually giving you READ COMMITTED.

Databases that operate with read locks usually use READ UNCOMMITTED to work around that limitation, but it is difficult to come up with use cases in PostgreSQL.

Upvotes: 2

Related Questions