Hibernate Services
Hibernate provides a variety of services to you, whether through native Hibernate libraries or third-party libraries that you can download along with the core framework. For the purposes of this chapter, we’ll examine just three: transaction management, caching support, and security. Many others are available, and you can learn about them in Hibernate’s excellent online documentation.
Transactions
Most database applications require transactions in order to provide some level of assurance around
updates to the tables. Hibernate provides a fully ACID-compliant
local transaction manager for use with applications talking to a
single database.[68] You can make use of the transaction provider with
minimal effort, but it is often useful to be explicit about your use
of transactions in your data code. This means making use of
Hibernate’s Transaction
object.
When beginning transactional work against a single database,
you can explicitly begin a transaction within an open Session
:
Session session = factory.openSession(); Transaction tx = session.beginTransaction();
Remember that the Session
object does not actually grab a JDBC connection from the pool until
you make a call that requires data access. The call to beginTransaction
forces the Session
to retrieve a connection because a
transaction is meaningless without a connection as context.
Once a transaction has been established, you can do your data
work. Any usage of the Session
to
access the database between the call to
Get Java Enterprise in a Nutshell, Third Edition 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.