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>
posted @ 2018-07-02 11:48  城南少年与猫  阅读(485)  评论(0编辑  收藏  举报