UML Overview of this example:
BaseDAO is an extension of GenericDAO and it must be extended by each DAO class of the project.
JPAGenericDAO is a generic, abstract class to be extended by each concrete DAO class.
Sample code:
- /**
- * @author Hasan Oezdemir
- * @since 01.10.2011
- *
- */
- public abstract class JPAGenericDAO<T, ID extends Serializable> extends GenericDAOImpl<T, ID> implements
- BaseDAO<T, ID> {
- private static final Logger logger = LoggerFactory.getLogger(JPAGenericDAO.class);
- @PersistenceContext(unitName="scheduling")
- private EntityManager entityManager;
- public JPAGenericDAO(){
- super();
- }
- @PostConstruct
- public void initialized(){
- logger.info( "initializing generic dao, setting entity manager: {}", entityManager);
- this.setEntityManager(entityManager);
- JPASearchProcessor searchProcessor = new JPASearchProcessor(new JPAAnnotationMetadataUtil());
- this.setSearchProcessor(searchProcessor);
- }
- public T findByExampleUnique(T example) {
- Search s = this.createSearch(example);
- return searchUnique(s);
- }
- public Collection<T> findByExample(T example) {
- Search s = this.createSearch(example);
- return search(s);
- }
- protected Search createSearch(T example) {
- Search s = new Search(example.getClass());
- s.addFilter(this._getFilterFromExample(example));
- return s;
- }
- }
UserDAO extends the BaseDAO :
- /**
- * @author Hasan Oezdemir
- * @since 01.10.2011
- *
- */
- public interface UserDAO extends BaseDAO<User, Long> {
- }
and a sample reference implementation of DAOs :
- /**
- * @author Hasan Oezdemir
- * @since 01.10.2011
- *
- */
- @Singleton
- public class JPAUserDAO extends JPAGenericDAO<User, Long> implements UserDAO {
- public JPAUserDAO(){
- super();
- }
- }
We keep basic CRUD operations in our abstract class but we have also seperate interfaces to provide 'Model' specific method and keep them seperate from generic DAO solutions.
Keine Kommentare:
Kommentar veröffentlichen