JPA_Hibernate_Interview_Problems
JPA_Hibernate_Interview_Problems
How does JPA manage entity lifecycle and what are the key states?
JPA entities can be in one of the following states:
New (Transient): not associated with persistence context.
Managed (Persistent): associated with EntityManager and tracked for changes.
Detached: was persistent, but EntityManager is closed or cleared.
Removed: marked for deletion but not yet deleted from DB.
EntityManager operations:
persist(): makes new entity persistent.
merge(): copies state into a managed entity.
detach(): removes from persistence context.
remove(): marks entity for deletion.
What are the differences between fetch types EAGER and LAZY in JPA?
EAGER:
Related entities are fetched immediately using JOINs.
May cause N+1 problems or performance overhead.
LAZY:
Related entities are loaded only when accessed.
Requires open persistence context; otherwise, LazyInitializationException.
Best practice:
Use LAZY by default and explicitly JOIN FETCH when necessary.