码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-12-09 15:40:42      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:blog   io   ar   os   sp   java   on   2014   log   

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();
	}

	
}

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

标签:blog   io   ar   os   sp   java   on   2014   log   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!