The last post introduced a basic implementation using Hibernate.
At the end, few lines presented a secure way to store data into the database, with the ability of undoing the changes in case of failure (rollback).
Usually, read and write operations are extensively used along the application.
A good practice, however, is that its business logic should be decoupled from the data storage to guarantee a uniform and reliable data persistence.
In other words, the business logic of the application should not be concerned about how and where the information is stored.
This intermediate entity is usually a Data Access Object (DAO), that provides simple CRUD (create, read, update, delete) methods to the upper layer, and handle the transactions with the database, the bottommost layer.
The respective DAO for the previous post using Hibernate can be implemented as follows:
Every DAO instantiate a SessionFactory once.
The method getSessionFactory() is then invoked every time a new transaction has to be performed.
Following it is shown the implementations of methods addAlarm(...), updateAlarm(...) and deleteAlarm(...).
In every method above, a Transaction is started for a session.
If something unexpected happens while the write operation fails, the transaction is undone and the session closed.
The flush() method forces Hibernate to synchronize the in-memory state of the session with the database.
Through this DAO, the higher layers of the application are then able to persist information into the database in a transparent way:
As a result, the business logic can change and invoke the DAO methods in different contexts without need to change the DAO itself.
Similarly, any modification related to the ORM implementation (Hibernate in this case) will be reflected up to the DAO, so that the usage by the business logic remains untouched as long as the signature of the DAO methods are kept.