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)
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
