If you are working with object-orientated programming and relational
databases, you will surely have noticed that these are two different
paradigms. The relational model deals with relations,tuples and sets -
it is very mathematical by nature. The object-orientated paradigm
however deals with objects, their atributes and associations to each
other. As soon as you want to make objects persistent using a
relational database you will notice: There is a rift between these two
paradigms, the so called object-relational gap. A object-relational
mapper (or ORM as a shorthand) will help you bridge that gap.
Well, how does this gap manifest? If you are passing objects around in
your application and sometimes reach the point where you want to
persist them, you will typically open a JDBC connection, create an SQL
statement and copy all your property values over to the
PreparedStatement or into the SQL string you are building. This may be
easy for a small value object - but consider this for an object with
many properties. Thats not the only problem. What about associations?
If your Cat object you want to store has a List of kittens contained?
Do you store them too? Automatically? Manually? What about foreign key
The same applies for loading - let's assume you load a Cat object from
the database and it has a collection of kittens. Do you load the
kittens too? Not load them yet but later? If you load the kittens,
consider each of the kitten object has an association to yet more
objects. In this case, such eager loading may easily load your
complete object tree. Not loading the kittens is however not really
better however - you will need explicit reloading later if you
probably want to access the kittens.
As you can see, the object-relational gap quickly becomes very wide if
you have large object models. And there are a lot more things to
consider like lazy loading, circular references, caching, etc. In
fact, there have been studies that showed that about 35% of an
application code was produced by the mapping between application data
and the datastore.
So what can an ORM do for you? A ORM basically intends to takes most
of that burden of your shoulder. With a good ORM, you have to define
the way you map your classes to tables once - which property maps to
which column, which class to which table, etc