Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generic DAO in Hibernate interface and abstract implementation
package com.bytestree.dao;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.springframework.beans.factory.annotation.Autowired;
@SuppressWarnings("unchecked")
public abstract class AbstractGenericDao<E> implements GenericDao<E> {
private final Class<E> entityClass;
public AbstractGenericDao() {
this.entityClass = (Class<E>) ((ParameterizedType) this.getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
}
@Autowired
private SessionFactory sessionFactory;
protected Session getSession() {
return this.sessionFactory.getCurrentSession();
}
@Override
public E findById(final Serializable id) {
return (E) getSession().get(this.entityClass, id);
}
@Override
public Serializable save(E entity) {
return getSession().save(entity);
}
@Override
public void saveOrUpdate(E entity) {
getSession().saveOrUpdate(entity);
}
@Override
public void delete(E entity) {
getSession().delete(entity);
}
@Override
public void deleteAll() {
List<E> entities = findAll();
for (E entity : entities) {
getSession().delete(entity);
}
}
@Override
public List<E> findAll() {
return getSession().createCriteria(this.entityClass).list();
}
@Override
public List<E> findAllByExample(E entity) {
Example example = Example.create(entity).ignoreCase().enableLike().excludeZeroes();
return getSession().createCriteria(this.entityClass).add(example).list();
}
@Override
public void clear() {
getSession().clear();
}
@Override
public void flush() {
getSession().flush();
}
}
package com.bytestree.dao;
import java.io.Serializable;
import java.util.List;
/**
* Interface to provide common DAO methods
*
*/
public interface GenericDao<E>
{
/**
*
* @param entity: entity to save
* @return Identifier of saved entity
*/
Serializable save(E entity);
/**
*
* @param entity:entity to save or update
*/
public void saveOrUpdate(E entity);
/**
*
* @param entity: entity to delete
*/
void delete( E entity );
/**
* Delete all records
*/
void deleteAll();
/**
* Find all records
* @return
*/
List<E> findAll();
/**
* Find all records matching provided entity
* @param entity: entity object used for search
* @return
*/
List<E> findAllByExample( E entity );
/**
* Find by primary key
* @param id
* @return unique entity
*/
E findById( Serializable id );
/**
* Clear session
*/
void clear();
/**
* Flush session
*/
void flush();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.