With ORMs such as JPA and Hibernate, simple CRUD operations are usually near-one-liners, and almost the same across entities/tables for each type of database access. Queries, especially more complicated ones, can require a few lines of code to make and execute. They also have a number of similarities across them.
With that in mind, it is natural to design shared classes (e.g. base classes) for the CRUD operations.
If you prefer to use the Data Access Object design pattern, the base class is a natural fit. This is what the sidaof DAO base classes offer.
sidaof has a top level interface named Dao; all sidaof base DAOs implement it.
Contains common methods for all DAO implementations.
The base DAO interface for JPA usage.
The base DAO for JPA. It contains the main logic, but obtains the EntityManager from a subclass.
The convenience base DAO for JPA and has an instance of the default EntityManager.
Convenience class, primarily for creating DAO testing stubs, that implements no-op methods of JpaDao interface.
The base DAO interface for Hibernate usage.
The base DAO for Hibernate. It contains the main logic, but obtains the Session from a subclass.
The convenience base DAO for Hibernate, having the SessionFactory and returns the getCurrentSession().
Convenience class, primarily for creating DAO testing stubs, that implements no-op methods of HibernateDao interface.
public class PersonDao extends JpaDao<Long, Person> { }
@Repository @Transactional(propagation = Propagation.MANDATORY) public class PersonJpaDao extends JpaDaoImpl<Long, Person> implements PersonDao { }
Note the Long and Person types specified for the primary key and managed entity types. Refer to the JavaDoc for argument notes.
Alternatively, when needing to specify the persistence unit name, extend the correct ORM base class, such as AbstractJpaDao class, and implement the needed method(s). For example:
@Repository @Transactional(propagation = Propagation.MANDATORY) public class PersonJpaDao extends AbstractJpaDao<Long, Person> implements PersonDao { @PersistenceContext(unitName="persistenceUnitName") protected EntityManager entityManager; @Override public EntityManager getEntityManager() { return entityManager; } @Override public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } }