liveBook · Manning

Phantom read

As explained in Java Persistence with Spring Data and Hibernate epub

A phantom read is a concurrency anomaly in which repeated query executions within a transaction return different sets of rows because another transaction inserted or deleted matching data.

A phantom read occurs when a transaction runs a query again and gets a different set of results because another transaction inserted or deleted matching data. The queries need not be exactly identical. Unlike an unrepeatable read, which concerns a changed data item, a phantom read concerns data appearing in or disappearing from a result set. section 11.2.1

A new matching item

Transaction 1 queries items in a category. Transaction 2 inserts a matching item and commits. When Transaction 1 queries again, the new item appears: it is the phantom. section 11.2.1

Isolation determines whether this can happen. READ_COMMITTED and REPEATABLE_READ permit phantom reads; SERIALIZABLE prevents them. Stronger isolation carries performance and scalability costs. section 11.2.1

Table 11.1 ANSI isolation levels and the problems that they address (view table figure)

Isolation level

Phantom read

Unrepeatable read

Dirty read

Lost update

READ_UNCOMMITTED

–

–

–

+

READ_COMMITTED

–

–

+

+

REPEATABLE_READ

–

+

+

+

SERIALIZABLE

+

+

+

+

Compare phantom reads with the other concurrency anomalies across the ANSI isolation levels. section 11.2.1

For explicit JPA locking, PESSIMISTIC_READ guarantees repeatable reads, while PESSIMISTIC_WRITE additionally guarantees that no phantom reads occur. Hibernate’s locking SQL depends on the database dialect. A pessimistic lock lasts only for its database transaction, and failure to obtain it raises an exception. section 11.2.3

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Defines the anomaly and compares isolation guarantees, then explains JPA lock modes and transaction duration without detailing their database implementations.
Examples
Illustrates a second query seeing newly inserted data and compares isolation levels in an anomaly table.
What it assumes
Assumes familiarity with transactions and queries while defining the anomaly before introducing isolation-level guarantees.
What you can do after
Apply it via JPA PESSIMISTIC_WRITE to prevent phantom reads within a database transaction while accounting for lock acquisition failures.
How it connects
Relates phantom reads to unrepeatable reads, ANSI isolation levels, pessimistic locking, and JPA lock modes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.