A whirlwind tour of ORM
A persistence layer is a basic part of a well-designed web application. I’m deliberately using
the English term “persistence layer” because the Czech equivalent of “data layer” strikes me as a little misleading
in the context of a three-tier model.
Why a persistence layer and ORM?
The main job of the persistence layer is to shield higher layers, especially the business layer,
from a particular data source. The nice thing is that you can easily swap the backend, the data source,
without changing the application code.
There are several ways to achieve this, but I’d venture that the most widely used
is object-relational mapping, or ORM. The mapping
is how we express relations as objects.
Suppose our relational database has a table for employees and another for their
phone numbers. We map them to two kinds of object, one corresponding to the employee
table (whose columns correspond to the object’s interface) and the other to the phone-number table.
We also express the one-to-many relationship between employee and phone number. In the object model
that relationship takes the form of nested collections.
In the application logic we write the equivalent of SQL queries for our ORM framework.
Hibernate, for example, has HQL (Hibernate Query Language).
A query returns an object or a collection of objects. In our imaginary example, the query
select z from Zamestnanec z where z.prijmeni = ? would return one or more
Zamestnanec objects.
ORM frameworks offer a great interface for working with objects. Suppose we have
a form for adding new employees. Submitting it lets us
create a Zamestnanec object in the application logic. The mapping
associates it with the zamestnanec table. We then call the framework’s method
for persisting the object, and the employee is saved.
The need to specify a persistence layer led to JDO (Java Data Objects),
an interface that standardizes aspects that different frameworks had handled in their own way. For further reading,
I recommend Scott W. Ambler’s The Fundamentals of Mapping Objects to Relational Databases
and Richard Hightower’s Object-relation mapping without the container, or this comparison of ORM frameworks.
Related articles
Related CZ Podcast episodes
- #3 · Java 6 SE, Vývoj webových aplikací
Dagi and Filemon discuss Java 6 and web application frameworks. · Czech audio
- #1 · Vývojová prostředí v Javě
The first CZ Podcast episode looks at Java development environments. · Czech audio