genericDAO

in my jpa project i needed DAOs… Data Access Objects… and the concept to implement those should be generic… initially this concept is confusing as hell… but after that its kinda cool 🙂

Each Entity needs an DAO and for every entity there are 6 object involved:

  • interfcae GenericDao<T, K>: the main Interface with the basic DAO functions (CRUD(create, read, update, delete))
  • class GenericDaoImpl<T, K>: implements the GenericDao interface.
  • interface <entity>Dao: interface of the entity DAO, implements the GenericDao<<entityType>, <entityPrimaryKeyType>>
  • class <entity>DaoImpl: implementation of the entity Dao. it is extended by the GenericDaoImpl
  • class <entity>: the entity class
  • class <entity>DaoTest: testing rocks 🙂

confused? ok heres the example: partly in pseudo code…

Basic things:
public interface GenericDao<T, K extends Serializable>{
T findById(K id, boolean lock);
List<T> findAll();
T save(T entity);
void delete(T entity);
}

public abstract class GenericDaoImpl<T, K extends Serializable> implements GenericDao<T, K>

public Person{
  int id;
  string name
}

Person Dao:
public interface PersionDao extends GenericDao<Persion, Integer>

public class PersonDaoImpl extends GenericDaoImpl<Person, Integer> implements PersionDao

And thats it… in the GenericDaoImpl are all the methods for all entites and in the PersonDaoImpl the persion stuff…

Comments are closed.