The Hibernate API

Now that we’ve covered how to map your domain onto a database, we’ll examine using the Hibernate API to actually perform database operations. The various portions of the API are treated separately. A Hibernate application will usually make use of most of what you see here, though Interceptors and Events are somewhat less common than the others.

Configuration and Hibernate

Hibernate provides a class, org.hibernate.cfg.Configuration, that serves as the entry point to your application’s interaction with the database. You use the Configuration class to load mapping files, specify global options, and retrieve metadata about your schema and objects.

If you are using the hibernate.properties or hibernate.cfg.xml files and they are in the classpath of your application, the easiest way to configure Hibernate is to create an instance of Configuration and call the configure method:

Configuration cfg = new Configuration().configure();

The configure method can take no arguments, as shown, in which case Hibernate will search for the first matching configuration file. Optionally, you can pass a String, url, File, or Document to the method to load the configuration file from an alternate location.

This step needs to be taken only once per application lifetime. Parsing the configuration properties and establishing the global settings for Hibernate is a relatively lengthy and expensive process. The application should execute the step only once and cache the resulting instance of

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.