generic dao

package flight.dao;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.hibernate.Query;
import org.hibernate.SessionFactory;


public class GenericDao<T> {
 private SessionFactory sessionFactory ;

 public void setSessionFactory(SessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }
 
 @SuppressWarnings("unchecked")
 public  T get(Serializable id,Class<T> type){
  return (T) this.sessionFactory.getCurrentSession().get(type.getClass(), id);
 }
 
 public Serializable save(T t){
  return this.sessionFactory.getCurrentSession().save(t) ;
 }
 
 public void persist(T t){
  this.sessionFactory.getCurrentSession().persist(t) ;
 }
 
 public void delete(T t){
  this.sessionFactory.getCurrentSession().delete(t);
 }
 
 public void update(T t){
  this.sessionFactory.getCurrentSession().update(t);
 }
 
 @SuppressWarnings("unchecked")
 public List<Object> findByNamedQuery(String namedQueryName){
  return this.sessionFactory.getCurrentSession().getNamedQuery(namedQueryName).list();
 }
 
 @SuppressWarnings("unchecked")
 public List<Object> findByNamedQuery(String namedQueryName,int resultLimit){
  return this.sessionFactory.getCurrentSession()
  .getNamedQuery(namedQueryName).setMaxResults(resultLimit).list();
 }
 
 public List<Object> findByNamedQuery(String namedQueryName,
   Map<String, Object> parameters) {
  return this.findByNamedQuery(namedQueryName, parameters,0, 0);
 }
 
 @SuppressWarnings("unchecked")
 public List<Object> findByNamedQuery(String namedQueryName,
   Map<String, Object> parameters,int startIndex,int resultLimit) {
  Query query = this.sessionFactory.getCurrentSession().getNamedQuery(
    namedQueryName);
  Set<Entry<String, Object>> rawParameters = parameters.entrySet();

  for (Entry<String, Object> entry : rawParameters) {
   query.setParameter(entry.getKey(), entry.getValue());
  }
  
  if (startIndex != 0)
   query.setFirstResult(startIndex);
  
  if(resultLimit > 0)
   query.setMaxResults(resultLimit);
  
  return query.list();
 }
 
 
 
 
 

 
 

}

posted on 2010-08-10 20:43  sunliho  阅读(1094)  评论(0编辑  收藏  举报