public interface RootDAO<T> extends Serializable {
public List<T> loadAll();
public T save(T entity);
public void delete(T entity);
public void markAsDeleted(T entity);
public T get(Serializable id);
public T load(Serializable id);
public void saveOrUpdate(T entity);
public void deleteAll(Collection<T> entities);
public void saveOrUpdateAll(Collection<T> entities);
public List<T> find(String hql);
public void update(T entity);
public T getByExampleUnique(T entity);
public List<T> getByExampleList(T entity);
public List<T> listAll();
public Object execute(HibernateCallback action);
public List<T> findByNamedParam(String queryString, String paramName,Object value);
public List<T> findByNamedParam(String queryString, String[] paramNames,Object[] values);
.
.
.
.
}
@Component
public abstract class RootDAOImpl<T> extends HibernateDaoSupport implements RootDAO<T> {
protected Logger logger = LoggerFactory.getLogger(getClass());
private Class<T> clazz;
@Autowired
public void init(SessionFactory factory) {
setSessionFactory(factory);
}
public RootDAOImpl(Class<T> clazz) {
this.clazz = clazz;
}
public void delete(T entity) {
getHibernateTemplate().delete(entity);
}
public void delete(String id) {
getHibernateTemplate().delete(new FbUser(id));
}
public void markAsDeleted(T entity) {
// Mark entity as deleted
try {
Method setDeletedMethod = clazz.getDeclaredMethod("setDeleted", Boolean.class);
setDeletedMethod.invoke(entity, true);
getHibernateTemplate().saveOrUpdate(entity);
} catch (Exception e) {
e.printStackTrace();
}
// actually delete
// getHibernateTemplate().delete(entity);
}
@Override
public void deleteAll(Collection<T> entities) {
getHibernateTemplate().deleteAll(entities);
}
@Override
public void saveOrUpdateAll(Collection<T> entities) {
getHibernateTemplate().saveOrUpdateAll(entities);
}
@SuppressWarnings("unchecked")
@Override
public T get(Serializable id) {
return (T) getHibernateTemplate().get(clazz, id);
}
@SuppressWarnings("unchecked")
@Override
public T load(Serializable id) {
return (T) getHibernateTemplate().load(clazz, id);
}
@SuppressWarnings("unchecked")
@Override
public List<T> find(String hql) {
return (List<T>) getHibernateTemplate().find(hql);
}
@Override
public Object execute(HibernateCallback action) {
return getHibernateTemplate().execute(action);
}
.
.
.
}
@Repository
public class UserDAOImpl extends RootDAOImpl<User> implements UserDAO{
public UserDAOImpl() {
super(User.class);
}
}
如果您不使用 DI 框架,则可能需要保留 SessionFactory 的引用并在创建 DAO 实例时自行传递。