dao 层封装(利用spring + hibernate)

接口 baseDao

 

package com.dx.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.SQLQuery;

public interface BaseDao {

	public void save(Object object);
	
	public void update(Object object);
	
	public void delete(Object object);
	
	public <T> T get(Class<T> type,Serializable id);
	
	public List<?> query(String hql);
	
	public List<?> query(String hql,int pageNum,int pageSize);
	
	public List<?> queryBySql(String sql);
	
	public List<?> queryBySql(String sql,int pageNum,int pageSize);
	
		
	
}

 

baseDaoImpl

 

package com.dx.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.dx.dao.BaseDao;

public class BaseDaoImpl extends HibernateDaoSupport implements BaseDao{

	private SessionFactory sessionFactory;
	
	public void setSuperSessionFactory(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}
	
	@Override
	public void save(Object object) {
		this.getHibernateTemplate().save(object);
	}

	@Override
	public void update(Object object) {
		this.getHibernateTemplate().update(object);
		
	}

	@Override
	public void delete(Object object) {
		this.getHibernateTemplate().delete(object);
	}

	@Override
	public <T> T get(Class<T> type, Serializable id) {
		return this.getHibernateTemplate().get(type, id);
	}

	@Override
	public List<?> query(String hql) {
		return this.getHibernateTemplate().find(hql);
	}

	@Override
	public List<?> query(String hql, int pageNum, int pageSize) {
		
		List<?> list=null;
		Session session = this.getSession();
		Transaction transaction = session.beginTransaction();
		
		transaction.begin();
		
		Query query = session.createQuery(hql);
		query.setFirstResult(pageNum*pageSize);
		query.setMaxResults(pageSize);
		list = query.list();
		
		transaction.commit();
		session.close();
		return  list;
	}

	@Override
	public List<?> queryBySql(String sql) {
		List<?> list=null;
		Session session = this.getSession();
		Transaction transaction = session.beginTransaction();
		
		transaction.begin();
		
		SQLQuery sqlQuery = session.createSQLQuery(sql);
		
		list = sqlQuery.list();
		transaction.commit();
		session.close();
		return list;
	}
	
	@Override
	public List<?> queryBySql(String sql, int pageNum, int pageSize) {
		List<?> list=null;
		Session session = this.getSession();
		Transaction transaction = session.beginTransaction();
		
		transaction.begin();
		
		SQLQuery query = session.createSQLQuery(sql);
		query.setFirstResult(pageNum*pageSize);
		query.setMaxResults(pageSize);
		list = query.list();
		
		transaction.commit();
		session.close();
		return  list;
	}

			

}

 

ok

 

 

你可能感兴趣的:(DAO)