Hibernate Framework Hibernate Transactions 2 — Questions and Answers
Question 1: Which LockMode acquires a pessimistic write lock in Hibernate?
- LockMode.PESSIMISTIC_WRITE (Correct answer)
- LockMode.WRITE
- LockMode.EXCLUSIVE
- LockMode.LOCK
Correct answer: LockMode.PESSIMISTIC_WRITE
LockMode.PESSIMISTIC_WRITE requests a SELECT FOR UPDATE lock, preventing other transactions from reading or writing the row.
Question 2: What is a StaleObjectStateException in Hibernate?
- Thrown when optimistic locking detects a concurrent modification (Correct answer)
- Thrown when a session is used after closing
- Thrown when a table does not exist
- Thrown when a null value is found
Correct answer: Thrown when optimistic locking detects a concurrent modification
StaleObjectStateException is thrown when a commit detects that another transaction has already modified the same versioned entity.
Question 3: What is the difference between session.save() and session.persist() in Hibernate?
- save() returns the generated ID immediately; persist() is JPA-standard and returns void (Correct answer)
- persist() is faster than save()
- save() only works inside transactions; persist() does not
- They are identical
Correct answer: save() returns the generated ID immediately; persist() is JPA-standard and returns void
save() immediately inserts the entity and returns the generated identifier, while persist() is the JPA-standard method that schedules the insert and returns void.
Question 4: What does session.merge() do in Hibernate?
- Copies state from a detached entity into a new managed entity (Correct answer)
- Deletes and re-inserts an entity
- Merges two entities into one
- Synchronizes the session with the database
Correct answer: Copies state from a detached entity into a new managed entity
merge() takes a detached entity, copies its state into a managed entity with the same identifier, and returns the managed instance.
Question 5: What are the four entity states in Hibernate?
- Transient, Persistent, Detached, Removed (Correct answer)
- New, Active, Inactive, Deleted
- Unsaved, Saved, Updated, Deleted
- Open, Closed, Pending, Committed
Correct answer: Transient, Persistent, Detached, Removed
Hibernate entities cycle through four states: transient (not associated), persistent (managed), detached (was managed), and removed (scheduled for deletion).
Question 6: What does session.evict(entity) do in Hibernate?
- Removes the entity from the first-level cache without deleting from the database (Correct answer)
- Deletes the entity from the database
- Commits the entity changes
- Reloads the entity from the database
Correct answer: Removes the entity from the first-level cache without deleting from the database
evict() removes a specific entity from the Session's first-level cache, detaching it from the persistence context.
Which LockMode acquires a pessimistic write lock in Hibernate?