Model and DAO Layer
In relational databases, data are represented in a tabular format, while in Java applications, data are represented in a interconnected graph of object format. While storing and retrieving an object model from a relational database, some mismatch occurs due to the following reasons:
- Granularity - Object model has more granularity than relational model.
- Subtypes - Inheritance is not supported by all types of relational databases.
- Associations - Relational models cannot determine multiple relationships while looking into an object domain model.
- Data navigation - data navigation between objects in an object network is different in both models.
Generally, Java developers use lots of code, or use a proprietary frameworks to interact with database. These frameworks (for example Toplink or Hibernate) reduces significantly the burden of interacting with relational databases. They form a bridge between object models (Java application) and relational models (database).
The Java Persistence API (JPA) is a vendor independent specification for mapping Java Objects to the tables of relational database. Implementations of this specification allow application developers to abstract from the specific database product they are working with and allow them to implement CRUD (Create, Read, Update, Delete) operations such that the same code works on different database products. These frameworks do not only handle the code that interacts with the database (the JDBC code) but also map the data to object structures used by the application.
The JPA consists of three different components:
- Entities - In current versions of the JPA entities are plain old Java objects (POJOs).
- Object-relational metadata - The application developer has to provide the mapping between the Java classes and their attributes to the tables and columns of the database. This can be done either trough dedicated configuration files or by using annotations. In this tutorial we will be use annotations.
- Java Persistence Query Language (JPQL) - As the JPA aims to abstract from the specific database product, the framework also provides a dedicated query language that can be used instead of SQL. This additional translation from JPQL to SQL allows the implementations of the framework to support different database dialects and allows the application developer to implement queries in a database independent way.