Chapter 5. Hibernate

Hibernate is a powerful and popular object-relational mapping (ORM) library and it forms the basis of the standard persistence layer in Grails. Hibernate addresses the “impedence mismatch” between object-oriented code and the relational database storage model. It also tries (and largely succeeds) in providing a mostly transparent persistent API where developers don’t need to consider the implementation details of storing and retrieving data because that’s handled under the hood.

Mapping Domain Classes

In general, you map a domain class to each table, although it’s common to partition tables into one or more classes (a domain class with components) and it’s also possible to map a domain class to multiple tables with a database view. Class properties map to database columns (which may be a foreign key to another table represented by its own domain class in a one-to-one or many-to-one relationship) or collections representing a one-to-many relationship with another domain class. Arrays of simple types are also supported, as are maps.

Traditionally, Hibernate applications used XML files (typically with a .hbm.xml file extension) to define the mapping between the code and the database. When annotations were added to Java in version 1.5, Hibernate added a more intuitive annotation-based mapping approach that keeps the metadata together with the code. Under the hood, however, Hibernate creates a metamodel of the domain classes (using the org.hibernate.cfg.HbmBinder ...

Get Programming Grails 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.