Ola amigos,
Gostaria de compartilhar com voces uma ideia que tive.
Cansado de implementar DAOs com trocentos metodos sobrecarregados, tipo:
List findAll();
List findAll(String orderBy);
List findAll(int firstResult, int maxResults);
List findAllByExample(Example o);
T findOneByExample(Example o);
etc. etc. Sem contar as possiveis combinacoes entre eles…
Resolvi refatorar um velho DAO e surgiu o seguinte:
public class Dao<T, K extends Serializable> {
protected Criteria c;
protected Session session;
protected Class<T> persistentClass;
public Dao(Session session, Class<T> persistentClass) {
this.session = session;
this.persistentClass = persistentClass;
}
public Dao<T, K> find() {
c = session.createCriteria(persistentClass);
return this;
}
public Dao<T, K> withActiveStatus(Boolean active) {
c.add(Restrictions.eq("active", active));
return this;
}
public Dao<T, K> withOrderByAsc(String propertyName) {
c.addOrder(Order.asc(propertyName));
return this;
}
public Dao<T, K> withOrderByDesc(String propertyName) {
c.addOrder(Order.desc(propertyName));
return this;
}
public Dao<T, K> withExample(T example) {
c.add(Example.create(example).enableLike(MatchMode.ANYWHERE).ignoreCase());
return this;
}
public Dao<T, K> withResults(int first, int max) {
c.setFirstResult(first);
c.setMaxResults(max);
return this;
}
public int count() {
c.setProjection(Projections.rowCount());
return (Integer) c.uniqueResult();
}
@SuppressWarnings("unchecked")
public List<T> all() {
return c.list();
}
@SuppressWarnings("unchecked")
public T one() {
return (T) c.uniqueResult();
}
}
Alguns exemplos de utilizacao:
List<User> allUsers = userDao.find().all();
List<User> activeUsers = userDao.find().withActiveStatus(true).all();
List<User> activeUsersSortedByName = userDao.find().withActiveStatus(true).withOrderByAsc("name").all();
List<User> veryVerySpecific = userDao.find().withActiveStatus(true).withOrderByAsc("name").withResults(0, 25).all();
List<Product> topTenExpensive = productDao.find().withOrderByDesc("price").withResults(0, 10).all();
Product foundByExample = productDao.find().withExample(product).one();
int activeGames = gameDao.find().withActiveStatus(true).count();
Sugestoes sao bem vindas…
Sds
wagner.montalvao