package cn.oa.base.dao.impl;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import cn.oa.base.dao.BaseDao;
@SuppressWarnings(“unchecked”)
public class BaseDaoImpl<T> implements BaseDao<T> {
@Resource
private SessionFactory sessionFactory;
private Class<T> clazz;
public Session getSession() {
return sessionFactory.getCurrentSession();
}
public BaseDaoImpl() {
/*
* 得到的是泛型化类
*/
ParameterizedType pt = (ParameterizedType) this.getClass()
.getGenericSuperclass();
/*
* 得到的是真实的类型
*/
this.clazz = (Class<T>) pt.getActualTypeArguments()[0];
}
@Override
public void add(T entry) {
getSession().save(entry);
}
@Override
public void edit(T entry) {
getSession().update(entry);
}
@Override
public void delete(Long id) {
T entry = getId(id);
getSession().delete(entry);
}
@Override
public List<T> findAll() {
List<T> list = getSession()
.createQuery(“FROM ” + clazz.getSimpleName())//
.list();
return list;
}
@Override
public T getId(Long id) {
getSession().get(clazz, id);
return null;
}
@Override
public List<T> getIds(Long[] ids) {
return getSession()
.createQuery(
“FROM ” + this.clazz.getSimpleName()
+ “WHERE id in(:ids)”)//
.setParameterList(“ids”, ids)//
.list();
}
}