java ssh DAO层增删改父类
刘振兴
代码分享
2016年09月20日
27812
5条评论
增加代码的复用性,减少代码的书写量
接口
import java.util.List;
/**
* 通用Dao接口
* @author zhaoqx
*
*/
public interface IBaseDao {
/**
* 添加
*/
public void save(T entity);
/**
* 根据id删除
*/
public void delete(Long id);
/**
* 根据id修改
*/
public void update(T entity);
/**
* 根据id查询
*/
public T getById(Long id);
/**
* 一次查询多个对象
*/
public List getByIds(Long[] ids);
/**
* 查询所有
*/
public List findAll();
}
实现
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import cn.itcast.oa.domain.Book;
/**
* 通用Dao实现
* @author zhaoqx
*
* @param
*/
@SuppressWarnings("unchecked")
public class BaseDaoImpl implements IBaseDao {
@Resource
private SessionFactory sessionFactory;
private Class clazz;
public BaseDaoImpl() {
//获得实体类型
ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();//获得真正的父类
Type[] types = genericSuperclass.getActualTypeArguments();
clazz = (Class) types[0];
}
public void save(T entity) {
getSession().save(entity);
}
public void delete(Long id) {
getSession().delete(getSession().get(clazz, id));
}
public void update(T entity) {
getSession().update(entity);
}
public List findAll() {
String hql = "FROM " + clazz.getSimpleName();
return getSession().createQuery(hql).list();
}
public T getById(Long id) {
return (T) getSession().get(clazz, id);
}
public List getByIds(Long[] ids) {
String hql = "FROM " + clazz.getSimpleName() + " WHERE id in (:ids)";
Query query = getSession().createQuery(hql);
query.setParameterList("ids", ids);//一次赋值多个
return query.list();
}
public Session getSession(){
return sessionFactory.getCurrentSession();
}
}
评论一下
赞助本站
版权申明:此文如未标注转载均为本站原创,自由转载请表明出处《IT技术宅》。
本文网址:https://www.ilt.me/dmfx/107.html