A JPA persistence context caches persistent entity instances during a unit of work. Hibernate also keeps state snapshots so it can detect changes and synchronize them with the database. This is useful when working with entities, but loading thousands of instances just to read them can consume substantial memory. section 10.2.8
The cache does not shrink automatically. Query only the data needed, especially when an entity graph could be large. Use `EntityManager.detach(entity)` to remove one instance or `EntityManager.clear()` to detach them all. For thousands of row changes, consider a bulk data operation instead of keeping thousands of entities in the context. section 10.2.8
Hibernate offers read-only settings when loaded entities will not be edited:
- Set the entire persistence context to read-only through `Session.setDefaultReadOnly(true)`. section 10.2.8
- Mark one instance read-only with `Session.setReadOnly(entity, true)`, or request read-only query results through Hibernate’s query API or a JPA query hint. section 10.2.8
Path: managing-data2/src/test/java/com/manning/javapersistence/ch10 /ReadOnly.java – selectiveReadOnly() em.unwrap(Session.class).setDefaultReadOnly(true); #1 Item item = em.find(Item.class, ITEM_ID); item.setName("New Name"); em.flush(); #2 #1 Set the persistence context to read-only. #2 Consequently, <kbd>flush()</kbd> will not update the database.
The listing sets a read-only default before loading an entity. Changing its name and calling `flush()` consequently does not update the database. section 10.2.8
Read-only settings disable state snapshots and dirty checking for affected instances, but they require care: read-only entities can still be deleted, and mapped collections have special cases. Check those rules before relying on read-only behavior for a collection-bearing entity. section 10.2.8
Caching also affects what a transaction observes; it is not a substitute for choosing an appropriate database isolation level. Auto-commit mode cannot provide transaction-scoped snapshot isolation or repeatable reads based on read locks, even though the persistence context cache can help with repeated entity reads. Grouping reads within a system transaction gives their concurrency behavior a clearer scope. section 11.2.1 section 11.3.1





































