欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 中 BaseDao 在Hibernate中的用法

程序员文章站 2022-05-28 18:23:09
...

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