Chapter 7. Transactions and Security

In mountain biking and kayaking, the most thrilling moves are running ledges. It doesn't start that way in either sport. With kayaks, you tend to do a whole lot of work to set yourself up for a few seconds of freefall. You line up against a landmark, stroke hard to build speed, push your body forward, and then simultaneously thrust with your hips and paddle off of the edge, which launches you. With bikes, you tend to pick a line through that won't smash your chain ring, line your bike up, balance yourself behind the saddle so you don't fly over the handlebars, roll forward slowly, compress your shocks, jump up to lighten the bike, and hope for the best while you're falling.

Programmatic Transactions

Like most other services in Spring, you can use transactions programmatically or declaratively. When you're using a new service, it often makes sense to understand that service programmatically within a method before you break it out as a declarative service.

Sometimes, you want to hide services, and Spring certainly makes it easy to do so. Other times, you want to be explicit, such as when transactional logic is the central job of your method. Spring makes it easy to do transaction logic programmatically.

How do I do that?

You'll use the same mechanism for transactions as you do for JDBC: templates. For programmatic transactions, you'll use a TransactionTemplate. You'll put all of the code in the transaction body that you want to execute together.

Get Spring: A Developer's Notebook 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.