zoukankan      html  css  js  c++  java
  • 泛型baseDaoImpl类中如何知道具体子类的class类型

    package com.atguigu.surveypark.dao.impl;
    
    import java.lang.reflect.ParameterizedType;
    import java.util.List;
    
    import javax.annotation.Resource;
    
    import org.hibernate.Query;
    import org.hibernate.SessionFactory;
    
    import com.atguigu.surveypark.dao.BaseDao;
    
    /**
     * 抽象的dao实现,专门用于继承
     */
    @SuppressWarnings("unchecked")
    public abstract class BaseDaoImpl<T> implements BaseDao<T> {
    
    	//注入sessionFactory
    	@Resource
    	private SessionFactory sf ;
    	
    	private Class<T> clazz ;
    	
    	public BaseDaoImpl(){
    		//得到泛型话超类
    		ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
    		clazz = (Class<T>) type.getActualTypeArguments()[0];
    	}
    	
    	public void saveEntity(T t) {
    		sf.getCurrentSession().save(t);
    	}
    
    	public void saveOrUpdateEntity(T t) {
    		sf.getCurrentSession().saveOrUpdate(t);
    	}
    
    	public void updateEntity(T t) {
    		sf.getCurrentSession().update(t);
    	}
    
    	public void deleteEntity(T t) {
    		sf.getCurrentSession().delete(t);
    	}
    
    	/**
    	 * 按照HQL语句进行批量更新
    	 */
    	public void batchEntityByHQL(String hql, Object... objects) {
    		Query q = sf.getCurrentSession().createQuery(hql);
    		for(int i = 0 ; i < objects.length ; i ++){
    			q.setParameter(i, objects[i]);
    		}
    		q.executeUpdate();
    	}
    
    	public T loadEntity(Integer id) {
    		return (T) sf.getCurrentSession().load(clazz, id);
    	}
    
    	public T getEntity(Integer id) {
    		return (T) sf.getCurrentSession().get(clazz, id);
    	}
    
    	public List<T> findEntityByHQL(String hql, Object... objects) {
    		Query q = sf.getCurrentSession().createQuery(hql);
    		for(int i = 0 ; i < objects.length ; i ++){
    			q.setParameter(i, objects[i]);
    		}
    		return q.list();
    	}
    }
    

      

  • 相关阅读:
    高斯消元法
    DP:Making the Grade(POJ 3666)
    Heap:Sunscreen(POJ 3614)
    ShortestPath:Silver Cow Party(POJ 3268)
    ShortestPath:Wormholes(POJ 3259)
    ShortestPath:Six Degrees of Cowvin Bacon(POJ 2139)
    DP:Bridging Signals(POJ 1631)
    DP:Wooden Sticks(POJ 1065)
    Greedy:Protecting the Flowers(POJ 3262)
    Greedy:Stripes(POJ 1826)
  • 原文地址:https://www.cnblogs.com/zhenmingliu/p/4492683.html
Copyright © 2011-2022 走看看