Skip to content

Instantly share code, notes, and snippets.

@jacobheric
Created March 13, 2011 00:44
Show Gist options
  • Save jacobheric/867748 to your computer and use it in GitHub Desktop.
Save jacobheric/867748 to your computer and use it in GitHub Desktop.
A dao implementation that consolidates CRUD operations using Java generics
@Repository("baseDAO")
public abstract class BaseDAOImpl<T, ID extends Serializable> implements IBaseDAO<T, ID> {
@Autowired
protected SessionFactory sessionFactory; //injected by Spring container
@SuppressWarnings("unchecked")
private Class<T> clazz;
@SuppressWarnings("unchecked")
public BaseDAOImpl() {
this.clazz = (Class<T>)
((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
}
/** snipped boring CRUD **/
@SuppressWarnings("unchecked")
public List<T> findByExample(T exampleInstance, String[] excludeProperty) {
Criteria crit = this.sessionFactory.getCurrentSession().createCriteria(this.clazz);
Example example = Example.create(exampleInstance);
for (String exclude : excludeProperty) {
example.excludeProperty(exclude);
}
crit.add(example);
return crit.list();
}
/**
* Convenience criteria method.
*/
@SuppressWarnings("unchecked")
protected List<T> findByCriteria(Criterion...criterion) {
Criteria crit = this.getSessionFactory().getCurrentSession().createCriteria(this.clazz);
for (Criterion c : criterion) {
crit.add(c);
}
return crit.list();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment