ITeye博客

java 中 BaseDao 在Hibernate中的用法

as619864232 · 2012-07-02 17:41 · Java · Hibernate · 编程语言 · Java · Hibernate · ParameterizedType · Markdown

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public abstract class BaseDao<T> {
	private SessionFactory sessionFactory;

	private Class clazz;

	public BaseDao() {
		super();
		clazz = getParameterizedTypeByParent(super.getClass());
	}

	private Class getParameterizedTypeByParent(Class clazz) {
		Type tp = clazz.getGenericSuperclass();
		if (tp instanceof ParameterizedType) {
			return (Class) ((ParameterizedType) tp).getActualTypeArguments()[0];
		} else {
			throw new ClassCastException("this is not ParameterizedType type");
		}
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public List findAll() {
		List results = getSession().createCriteria(clazz).list();
		return results;
	}

	public T findById(Integer id) {
		T result = (T) getSession().get(clazz, id);
		return result;
	}

	public void update(T obj) {
		getSession().save(obj);
	}

	private Session getSession() {
		return sessionFactory.getCurrentSession();
	}
}

评论(1)

  1. #1 楼 · sunday1207 · 2015-05-24 23:42

    private Class getParameterizedTypeByParent(Class clazz) {
    Type tp = clazz.getGenericSuperclass();
    if (tp instanceof ParameterizedType) {
    return (Class) ((ParameterizedType) tp).getActualTypeArguments();
    } else {
    :D ---直接在车里报异常了如何处理 throw new ClassCastException("this is not ParameterizedType type");
    }
    }

评论功能维护中,当前仅展示历史评论。