zoukankan      html  css  js  c++  java
  • java的SSH的baseDao,巧用泛型

    BaseDao接口:

    import java.util.List;
    public interface BaseDao<T,PK> {
    
    	public void add(T t);
    	
    	public void upd(T t);
    	
    	public void del(PK id);
    	
    	public T getById(PK id);
    	
    	public List<T> getAll();
    
    	public List<Track> getByAid(String activityId);
    	
    	
    	
    }
    
    

    BaseDaoImple:

    import java.io.Serializable;
    import java.lang.reflect.ParameterizedType;
    import java.lang.reflect.Type;
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.orm.hibernate5.HibernateTemplate;
    
    public class BaseDaoImple<T, PK> implements BaseDao<T, PK> {
    	// 保存当前类处理的实体类型对象类型
    	private Class clazz;
    
    	public BaseDaoImple() {
    
    		Type clas = this.getClass().getGenericSuperclass();
    
    		ParameterizedType pt = (ParameterizedType) clas;
    
    		Type[] ts = pt.getActualTypeArguments();
    
    		// 获取第一个泛型类型
    		clazz = (Class) ts[0];
    	}
    
    	@Autowired
    	private HibernateTemplate hibernateTemplate;
    
    	@Override
    	public void add(T t) {
    
    		hibernateTemplate.save(t);
    
    	}
    
    	@Override
    	public void upd(T t) {
    		hibernateTemplate.update(t);
    
    	}
    
    	@Override
    	public void del(PK id) {
    		hibernateTemplate.delete(this.getById(id));
    	}
    
    	@Override
    	public T getById(PK id) {
    
    		return (T) hibernateTemplate.get(clazz, (Serializable) id);
    	}
    
    	@Override
    	public List<T> getAll() {
    		return hibernateTemplate.loadAll(clazz);
    	}
    
    	@Override
    	public List<Track> getByAid(String activityId) {
    
    		String queryString = "from Track where activity.activityId = ?";
    
    		return (List<Track>) hibernateTemplate.find(queryString, activityId);
    
    	}
    
    }
    
    
    <listener>
    	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
  • 相关阅读:
    [CF1166E] The LCMs Must be Large
    AtCoder Beginner Contest 161
    [CF1168B] Good Triple
    [CF1172B] Nauuo and Circle
    [CF1185E] Polycarp and Snakes
    [CF1187E] Tree Painting
    Codeforces Round #631 (Div. 2)
    [CF1200E] Compress Words
    Thinkphp绕过宝塔getshell
    如何成为一个漏洞赏金猎人
  • 原文地址:https://www.cnblogs.com/charlypage/p/9253135.html
Copyright © 2011-2022 走看看