首页 > 其他 > 详细

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

时间:2014-12-09 15:37:50      阅读:259      评论:0      收藏:0      [点我收藏+]
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();
	}

	
}

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

原文:http://blog.csdn.net/fuleidemo/article/details/41824613

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!