Hibernate Framework Hibernate Transactions 1 — Questions and Answers
Question 1: How do you begin a transaction in Hibernate using the Session API?
- session.beginTransaction() (Correct answer)
- session.startTransaction()
- session.openTransaction()
- session.newTransaction()
Correct answer: session.beginTransaction()
The beginTransaction() method on a Hibernate Session starts a new database transaction and returns a Transaction object.
Question 2: What happens if you call session.flush() inside a transaction?
- Hibernate synchronizes in-memory state with the database without committing (Correct answer)
- The transaction is committed
- The session is closed
- All cached objects are cleared
Correct answer: Hibernate synchronizes in-memory state with the database without committing
flush() forces Hibernate to execute pending SQL statements to synchronize the persistence context with the database, but the transaction remains open.
Question 3: What does transaction.commit() do in Hibernate?
- Makes all changes permanent in the database and ends the transaction (Correct answer)
- Saves only a snapshot of changes
- Rolls back the transaction
- Flushes the session without persisting
Correct answer: Makes all changes permanent in the database and ends the transaction
commit() flushes the session if needed and then permanently saves all changes to the database, ending the current transaction.
Question 4: What is the role of transaction.rollback() in Hibernate?
- Undoes all changes made since the transaction began (Correct answer)
- Saves changes partially
- Closes the database connection
- Triggers a second flush
Correct answer: Undoes all changes made since the transaction began
rollback() reverses all database changes made within the current transaction, returning the database to its state before the transaction started.
Question 5: What is optimistic locking in Hibernate?
- Assumes no conflict and checks version at commit time (Correct answer)
- Locks rows immediately on read
- Prevents all concurrent access
- Requires explicit lock statements
Correct answer: Assumes no conflict and checks version at commit time
Optimistic locking assumes concurrent modifications are rare and only checks for conflicts at commit time using a version field.
Question 6: What is pessimistic locking in Hibernate?
- Acquires a database-level lock on rows when they are read (Correct answer)
- Checks for conflicts at commit time
- Disables concurrent access entirely
- Locks the entire table
Correct answer: Acquires a database-level lock on rows when they are read
Pessimistic locking acquires a database lock on the row as soon as it is read, preventing any other transaction from modifying it.
How do you begin a transaction in Hibernate using the Session API?