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

      

  • 相关阅读:
    Navicat12激活,最新版本v12.1.18,原版激活[windows]
    【工具】Fiddler使用教程
    MongoDB笔记
    MongoDB
    MySQL三层结构、用户权限、索引设计原则
    Ajax
    linux简单优化
    linux基本
    Memcached
    Django+Uwsgi+Nginx
  • 原文地址:https://www.cnblogs.com/zhenmingliu/p/4492683.html
Copyright © 2011-2022 走看看