EntityManager & Persistence Context — Concept Check
Questions on EntityManager & Persistence Context. The EntityManager is the gateway to JPA operations; the persistence context is its first-level cache holding managed entity instances for the duration of a transaction.
Questions in this quiz
8 questions on EntityManager & Persistence Context — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.During a transaction, you call em.find() twice with the same ID. What happens?
- AThe second call issues another SQL SELECT query.
- BThe second call returns the same instance from the L1 cache.
- CThe second call throws an exception due to duplicate ID.
- DThe second call updates the entity state to detached.
2.An entity is detached and you modify it. How do you persist these changes?
- AUse em.flush() to force changes to persist.
- BUse em.persist() to attach and persist changes.
- CUse em.remove() to delete and re-create the entity.
- DUse em.merge() to re-attach and persist changes.
3.What happens if you modify a managed entity's field without any explicit update call?
- AAn exception is thrown for modifying a managed entity.
- BThe change is ignored and not persisted.
- CThe change is automatically persisted on transaction commit.
- DThe entity becomes detached due to unsaved changes.
4.In a read-heavy transaction, which flush mode is most efficient?
- AFlushModeType.COMMIT
- BFlushModeType.IMMEDIATE
- CFlushModeType.MANUAL
- DFlushModeType.AUTO
5.You execute a JPQL query for an entity already in the persistence context. What happens?
- AThe query detaches the existing entity before fetching.
- BThe query uses the L1 cache and avoids a database hit.
- CThe query hits the database but merges the result into the context.
- DThe query throws an exception due to duplicate entities.
6.What is the role of the persistence context in JPA?
- AIt acts as a first-level cache for managed entities.
- BIt handles database connection pooling.
- CIt manages transaction isolation levels.
- DIt provides a second-level cache for queries.
7.After calling em.clear(), what is the state of previously managed entities?
- AThey are automatically merged back into the context.
- BThey become detached and are no longer tracked.
- CThey are removed from the database.
- DThey remain managed but are flushed to the database.
8.When does Hibernate automatically flush the persistence context?
- AOnly at transaction commit.
- BOnly when manually triggered.
- CBefore executing a query and at transaction commit.
- DBefore every entity operation.