package cn.itcast.oa.base;
import java.util.List;
public interface BaseDao<T> {
/**
* 儲存實體
* @param entity
*/
void save(T entity);
/**
* 刪除實體
* @param id
*/
void delete(Long id);
/**
* 更新實體
* @param entity
*/
void update(T entity);
/**
* 通過ID陣列查詢實體
* @param ids
* @return
*/
List<T> getByIds(Long[] ids);
/**
* 通過ID查詢實體
* @param id
* @return
*/
T getById(Long id);
/**
* 查詢全部實體
* @param entity
* @return
*/
List<T> findAll(T entity);
}
package cn.itcast.oa.base;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class BaseDaoImpl<T> implements BaseDao<T>{
@Resource
private SessionFactory sessionFactory;
private Class<T> clazz;
public BaseDaoImpl(){
ParameterizedType pt=(ParameterizedType) this.getClass().getGenericSuperclass();
this.clazz= (Class<T>) pt.getActualTypeArguments()[0];
System.out.println(clazz);
}
protected Session getSession(){
return sessionFactory.getCurrentSession();
}
public void delete(Long id) {
Object obj=getById(id);
if(obj!=null){
getSession().delete(obj);
}
}
public List<T> findAll(T entity) {
return getSession().createQuery("FROM"+clazz.getSimpleName()).list();
}
@SuppressWarnings("unchecked")
public T getById(Long id) {
return (T) getSession().get(clazz, id);
}
@SuppressWarnings("unchecked")
public List<T> getByIds(Long[] ids) {
return getSession().createQuery("FROM User WHERE id IN (?)").setParameterList("ids", ids).list();
}
public void save(T entity) {
getSession().save(entity);
}
public void update(T entity) {
getSession().update(entity);
}
}