SpringHibernateTemplateDemo

package zl.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import zl.dao.AbstractDao;

public abstract class AbstractDaoImpl extends HibernateDaoSupport 
								implements AbstractDao{
	
	public void saveEntity(Object entity){
		getHibernateTemplate().save(entity);
	}
	
	public void updateEntity(Object entity){
		getHibernateTemplate().update(entity);
	}
	
	public void deleteEntity(Object entity){
		getHibernateTemplate().delete(entity);
	}
	
	@SuppressWarnings("unchecked")
	public <T> T getEntityById(Class<T> type,int id){
		return (T)getHibernateTemplate().get(type,id);
	}
	
	@SuppressWarnings("unchecked")
	public <T> T loadEntityById(Class<T> type,int id){
		return (T)getHibernateTemplate().load(type,id);
	}
	
	@SuppressWarnings("unchecked")
	public <T> List<T> getAllEntitys(Class<T> type){
		StringBuffer sb = new StringBuffer();
		sb.append("from ").append(type.getName());
		return getHibernateTemplate().find(sb.toString());
	}
	
	@SuppressWarnings("unchecked")
	public <T> List<T> getEntitysByPage(final Class<T> type,final int first,final int size){		
		return (List<T>)getHibernateTemplate().execute(new HibernateCallback(){
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					StringBuffer sb = new StringBuffer();
					sb.append("from ").append(type.getName());
					return session.createQuery(sb.toString())
									.setFirstResult(first)
									.setMaxResults(size)
									.list();
				}});
	}
	
	@SuppressWarnings("unchecked")
	public int getEntityAllCount(Class type){
		StringBuffer sb = new StringBuffer();
		sb.append("select count(*) from ").append(type.getName());
		return Integer.parseInt(getHibernateTemplate()
								.find(sb.toString())
								.get(0)
								.toString());
	}
}

你可能感兴趣的:(DAO,sql,Hibernate,orm)