Skip to content

Notes on science, software and the craft of support

Martin EvansNotes and resources

Databases

Mapping objects to tables with Hibernate

A closer look at the mechanics of Hibernate: configuration, sessions, HQL and the features that keep Java objects in step with database tables.

Hibernate maps Java classes to database tables and Java data types to SQL data types. The mapping can be declared with annotations or with XML configuration, and the framework uses that metadata to generate the SQL that an application needs.

Applications work with a session, which represents a conversation between the application and the database. Objects are loaded, changed and saved through that session. Hibernate tracks the state of each object so that changes can be written back in a controlled way, and transactions make those changes atomic.

Queries and caching

Hibernate provides HQL, a query language that works with objects rather than table names. HQL supports joins, projections, aggregate functions and named parameters, and it keeps queries portable across databases. Native SQL is also available when a query needs a feature that only one database provides.

Caching and lazy loading are two of the features that make Hibernate practical. Caching reduces repeated database work, while lazy loading postpones the loading of related objects until they are needed. Optimistic locking helps detect conflicting updates without holding database locks for long periods.

Because the mapping is declared once and reused, an application can move between databases with relatively few changes. That portability, together with the query language and the session model, is why Hibernate remains a common choice for Java projects.