Junior — Middle
Can you show an example of using the commit() method in the context of Hibernate?
sobes.tech AI
Answer from AI
In Hibernate, the commit() method is used to finalize a transaction, meaning it saves all changes made within the current transaction to the database.
Example of usage:
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
// Create or modify objects
User user = new User();
user.setName("John");
session.save(user);
// Commit the transaction
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
Here, transaction.commit() saves all changes made in the session to the database. If an error occurs, the transaction is rolled back using rollback()."}]}]}