Efficiently loading associations with JDBC, Hibernate and EclipseLink
What is the best way to load relational data — JDBC or JPA?
Usually web applications serve to save data to a database and to visualize already saved data. What is the best way for a Java application to interact with a database? There are two options — JDBC or a library implementing JPA. Instead of speculating, I make a simple realistic experiment.
I suppose applications load data more often than save. So in this post I compare three options for loading relational data from a database. I compare JDBC to two JPA implementations — Hibernate and EclipseLink. The two JPA libraries are not equivalent. Some basic tasks that can be done in Eclipselink cannot be easily achieved with Hibernate, and conversely.
I will use the sample data model that resembles the
Employee relationships used in tutorials.
In my sample model, each country has many authors. Each author is a resident of one country. An author can create many posts. Each post is by one author. Chained one-to-many or many-to-many relations are omnipresent in real-life data. I do not use many-to-many only for the simplicity of the sample data, code, its output and thus this post. With many-to-many associations the conclusions would be the same.
Imagine that a view of a sample web application lists all the posts together with their authors and countries. The output is sorted by country, author and finally post:
I use three entities, that is classes each corresponding to a table. Normally entities have more fields but this post is about loading associations so each sample class has only an
id field and a
name. The two parent classes
Post have also a list containing the associated children.
Just by the way, obligatory id fields is a major limitation of JPA. Even if you want very much, you might not be able to…