首页 > 代码库 > 泛型持久层实现(深度减轻代码量)

泛型持久层实现(深度减轻代码量)

import java.math.BigDecimal;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class BaseDao {
	@Autowired
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> queryBaseObject(String sql, Class<T> entity) {
		return this.getSessionFactory().getCurrentSession().createSQLQuery(sql)
				.addEntity(entity).list();
	}

	public <T> void addBaseObject(T entity) {
		this.getSessionFactory().getCurrentSession().save(entity);
	}

	public <T> void updateBaseObject(T entity) {
		this.getSessionFactory().getCurrentSession().saveOrUpdate(entity);
	}

	public <T> void deleteBaseObject(T entity) {
		this.getSessionFactory().getCurrentSession().delete(entity);

	}

	public void insertOrUpdateObject(String sql) {
		this.getSessionFactory().getCurrentSession().createSQLQuery(sql)
				.executeUpdate();
	}

	@SuppressWarnings("unchecked")
	public <T> T querySingleObject(int id, Class<T> entity) {
		return (T) this.getSessionFactory().getCurrentSession()
				.load(entity, id);
	}

	@SuppressWarnings("unchecked")
	public <T> T querySingleobject(String sql, Class<T> entity) {
		return (T) this.getSessionFactory().getCurrentSession()
				.createSQLQuery(sql).addEntity(entity).uniqueResult();
	}

	@SuppressWarnings("rawtypes")
	public int queryListCount(String sql) {
		List gg = this.sessionFactory.getCurrentSession().createSQLQuery(sql)
				.list();
		int result = ((BigDecimal) gg.get(0)).intValue();
		return result;
	}

	public void deleteBaseObject(String sql) {
		this.getSessionFactory().getCurrentSession().createSQLQuery(sql)
				.executeUpdate();
	}

	
}

泛型持久层实现(深度减轻代码量)