当前位置: 首页 > 工具软件 > Generic DAO > 使用案例 >

generic dao

通正平
2023-12-01

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

 
 

}

转载于:https://www.cnblogs.com/sunliho/archive/2010/08/10/1796862.html

 类似资料:

相关阅读

相关文章

相关问答