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

      

  • 相关阅读:
    uva-712 S-Trees
    Liunx下文件权限详解
    uva-699 The Falling Leaves
    Oracle sql loader 使用案例
    设计模式学习--迭代器模式(Iterator Pattern)和组合模式(Composite Pattern)
    XML 简单介绍
    UVA 11107(Life Forms-后缀数组+二分)
    SRM 212 Div II Level One: YahtzeeScore
    HDU 5695 Gym Class 拓扑排序
    HDU 5694 BD String 迭代
  • 原文地址:https://www.cnblogs.com/zhenmingliu/p/4492683.html
Copyright © 2020-2023  润新知