Java persistence with Hibernate
Hibernate is an object-relational mapping (ORM) library for Java widely used in industry to provide a persistence of Java objects into relational databases.
The main purpose of Hibernate is to abstract the database operations so that developers could handle the objects without worries about the SQL calls and object conversions happening underneath the application. In fact, Hibernate generates the SQL queries playing the role of interface between the application and the database.
An extensive documentation can be found over the web, including at Hibernate’s website, where the library itself is also available for download. Since I’m using MySQL in this example, the respective connector for Java is required.
The configuration of Hibernate is described in the hibernate.cfg.xml
, usually located at the root of your project folder.
An example of its content is seem below.
The next step consists basically on mapping the attributes of your Java class to the fields of your database.
This mapping can be done either through Java Persistence Annotations (JPA) or by setting up an additional XML mapping file.
This example, specifically, uses the last method.
The respective mapping file should be included in the hibernate.cfg.xml
seen above.
Let’s start then by creating our class Alarm.java, with the attributes id, description and instant.
This class is a simple POJO object, with getters and setters for each attribute.
Note: Some IDEs (i.e. Eclipse) can generate the POJO class automatically from a database specification.
Given a table alarms with fields id, descr and instant, the respective mapping between Alarm.java and this table would be the following:
The first line within the <hibernate-mapping>
tag relates the Alarm.java class with the table alarms.
The primary key id receives a special tag where <id name="id"...>
corresponds to the Java attribute and the <column name="id"/>
to the database field. The id attribute is auto-generated.
The remaining properties follow the same principle, adding few other properties, such maximum length
and not-null
. See more properties here.
Finally, Hibernate uses sessions to persist the object to database.
This is the nearly the simplest way to setup and use Hibernate, although it is indeed a powerful tool with many other features.
The Hibernate Community Documentation is undoubtedly the best starting point.
The complete example including Data Access Objects (DAO) can be found in my repository.