Hibernate DAO的具体实现

定义BaseDAO: (增/删/改/查单个/查集合/查集合2)

 

public interface BaseDAO{
	<T>void add(T object);
	<T>void delete(Class clazz,Serializable id);
	<T>void update(T clazz);
	<T> T get(Class<T> clazz,Serializable id);
	<T>List<T>search(Class<T> clazz);
	<T>List<T> search(Class<T> clazz,Object condition);	
}

 

 然后再impl包中实现该接口:

 

public class BaseDAOSupport implements BaseDAO {

	private Session session;

	protected Session getSession() {
		return HibernateSessionFactory.getSession();
	}
	public void setSession(Session session) {
		this.session = session;
	}
	/**
	 * 增加
	 */
	public <T> void add(T object) {
		Transaction ts = null;
		try {
			ts = getSession().beginTransaction();
			getSession().save(object);
			ts.commit();
		} catch (HibernateException e) {
			if(null != ts){
				ts.rollback();
			}
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}		
		
	}
	/**
	 * 删除
	 */
	public <T> void delete(Class clazz,Serializable id) {
		Transaction ts = null;
		try {
			ts = getSession().beginTransaction();
			getSession().delete(get(clazz, id));
			ts.commit();
		} catch (HibernateException e) {
			if(null != ts){
				ts.rollback();
			}
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}		
	}
	/**
	 * 更新
	 */
	public <T> void update(T clazz) {
		Transaction ts = null;
		try {
			ts = getSession().beginTransaction();
			getSession().update(clazz);
			ts.commit();
		} catch (HibernateException e) {
			if(null != ts){
				ts.rollback();
			}
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}	
		
	}
	/**
	 * 查询单个
	 */
	public <T> T get(Class<T> clazz, Serializable id) {
		return (T) getSession().get(clazz, id);
	}
	/**
	 * 无条件查询集合
	 */
	public <T> List<T> search(Class<T> clazz) {
		List<T> list = getSession().createCriteria(clazz).list();
		return list ;
	}
	/**
	 * 有条件查询集合
	 */
	public <T> List<T> search(Class<T> clazz, Object condition) {
		List<T> list = getSession().createCriteria(clazz).add(Example.create(condition)).list();
		return list;
	}

}

 

 

你可能感兴趣的:(DAO,spring,Hibernate,框架)