spring+hibernate4整合dao

 

  1: package org.ssh2test1.dao;
  2: 
  3: import java.io.Serializable;
  4: import java.util.List;
  5: 
  6: import org.hibernate.Criteria;
  7: import org.hibernate.Session;
  8: import org.hibernate.SessionFactory;
  9: import org.hibernate.criterion.Criterion;
 10: import org.springframework.context.ApplicationContext;
 11: import org.springframework.context.support.ClassPathXmlApplicationContext;
 12: import org.ssh2test1.utils.ReflectionUtils;
 13: 
 14: 
 15: public class HibernateBaseDao<T, ID extends Serializable> {
 16: 	private Class<T> entityClass;
 17: 
 18: 	private static SessionFactory sessionFactory;
 19: 	private static Session session ;
 20: 	
 21: 	static {
 22: 		String[] configLocations = new String[] {"classpath:applicationContext-*.xml"};
 23: 		ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocations);
 24: 		sessionFactory = ctx.getBean("sessionFactory",SessionFactory.class);
 25: 	}
 26: 	
 27: 
 28: 	public static Session getSession() {
 29: 		return sessionFactory.openSession();
 30: 	}
 31: 	
 32: 	public HibernateBaseDao() {
 33: 		entityClass = ReflectionUtils.getSuperClassGenricType(getClass());
 34: 	}
 35: 
 36: 	public Criteria createCriteria(Criterion... criterions) {
 37: 		Criteria criteria = this.getSession().createCriteria(entityClass);
 38: 		for (Criterion criterion : criterions) {
 39: 			criteria.add(criterion);
 40: 		}
 41: 		return criteria;
 42: 	}
 43: 
 44: 	public List<T> getAll(Criterion... criterions) {
 45: 		return createCriteria(criterions).list();
 46: 	}
 47: 
 48: 	public T getById(ID id) {
 49: 		return (T) this.getSession().get(entityClass, id);
 50: 	}
 51: 
 52: 	public void save(Object entity) {
 53: 		this.getSession().save(entity);
 54: 	}
 55: 
 56: }
 57: 
posted @ 2014-04-10 16:59  疯狂馒头  阅读(1066)  评论(0编辑  收藏  举报