范类定义超类,简单易用

package com.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
/**
 * 实现增删改查的超类
 * @author Administrator
 *
 * @param <T>
 * @param <I>
 */
@Transactional
public class DaoSupport<T,I extends Serializable> {
 @Autowired protected SessionFactory factory;
 private Class<T> entityClass;
 @SuppressWarnings("unchecked")
 public DaoSupport() {
  Type genType = getClass().getGenericSuperclass();
  if(genType instanceof ParameterizedType){
   ParameterizedType pra=(ParameterizedType)genType;
   Type[] t=pra.getActualTypeArguments();
   if(t.length>0){
   entityClass=(Class<T>) t[0];
   }else{
   entityClass=(Class<T>) Object.class;
   }
  }else{
   entityClass=(Class<T>) Object.class;
  }
 }
 /**
  * 保存数据
  * @param entity
  */
 public void save(T entity) {
  factory.getCurrentSession().save(entity);
 }
 /**
  * 更新数据
  * @param entity
  */
 public void update(T entity){
  factory.getCurrentSession().update(entity);
 }
 /**
  * @param entity
  */
 public void delete(T entity){
  factory.getCurrentSession().delete(entity);
 }
 @SuppressWarnings("unchecked")
 public List<T> listAll(){
  return factory.getCurrentSession().createCriteria(entityClass).list();
  
 }
 @SuppressWarnings("unchecked")
 public T get(I id){
  return (T) factory.getCurrentSession().get(entityClass, id);
 }
 public final SessionFactory getFactory() {
  return factory;
 }

 public final void setFactory(SessionFactory factory) {
  this.factory = factory;
 }
}

你可能感兴趣的:(简单)