DAO
public interface BaseDao<T> {
void save(T entity);
void delete(Integer id);
void update(T entity);
T getById(Integer id);
List<T> getByIds(Integer[] ids);
List<T> findAll();
PageBean getPageBean(int pageNum,HqlHelper hqlHelper);//分页
}
DAOIMPL
public abstract class BaseDaoImpl<T> implements BaseDao<T> {
@Resource
private SessionFactory sessionFactory;//session工厂
private Class<T> clazz;
public BaseDaoImpl(){
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass(); // 获取父类类名
this.clazz =(Class<T>) pt.getActualTypeArguments()[0]; //取出类
}
/*获取当前可用session*/
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
@Override
public void save(T entity) {
getSession().save(entity);
}
@Override
public void delete(Integer id) {
Object obj = getById(id);
if(obj!=null){
getSession().delete(obj);
}
}
@Override
public void update(T entity) {
getSession().update(entity);
}
@Override
public T getById(Integer id) {
if(id==null){
return null;
}else{
return (T) getSession().get(clazz, id);
}
}
@Override
public List<T> getByIds(Integer[] ids) {
if(ids==null||ids.length==0){
return Collections.EMPTY_LIST;
}else{
return getSession().createQuery(//
"FROM"+clazz.getSimpleName()+"WHERE id IN (:ids)")//
.setParameterList("ids", ids)//
.list();
}
}
@Override
public List<T> findAll() {
return getSession().createQuery(//
"FROM " + clazz.getSimpleName())//
.list();
}