Handling transactions

If you want to perform multiple changes to the database as a single unit, that is, either all changes should be done or none, then you need to start a transaction in JDBC. You start a transaction by calling Connection. setAutoCommit(false). Once all operations are executed successfully, commit the changes to the database by calling Connection.commit. If for any reason you want to abort the transaction, call Connection.rollback(). Changes are not done in the database until you call Connection.commit.

Here is an example of inserting a bunch of courses into the database. Although in a real application, it may not make sense to abort a transaction when one of the courses is not inserted, here we assume that either all courses ...

Get Java EE 8 Development with Eclipse now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.