Hibernate 泛型Dao实现

package com.esailcar.finance.common.persistence;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.beans.factory.annotation.Autowired;


public class MyHibernateDao<T,P extends Serializable> {
    
    
    private Class<T> entityClass;    
    //可以整合到Spring中,直接用Autowired注解,不需要在构造函数生成
    private SessionFactory sessionFactory;
    
    @SuppressWarnings("deprecation")
    public MyHibernateDao()
    {
        this.entityClass=getTClass();
        Configuration config=new Configuration().configure("hibernate-cfg.xml");
        this.sessionFactory=config.buildSessionFactory();
    }
    
    public void save(final T entity)
    {
        getSession().saveOrUpdate(entity);
    }
    
    public T getById(final P id)
    {
        return (T) getSession().get(entityClass, id);
    }
    
    public List<T> getByHql(String queryString)throws SQLException{
            return getSession().createQuery(queryString).list();
    }
    private  Session getSession()
    {
        return sessionFactory.getCurrentSession();
    }
    private  Class<T> getTClass()
    {
        //获取直接超类的 Type 实例
        Type superClassType=getClass().getGenericSuperclass();
        try
        {
            if(superClassType instanceof ParameterizedType)
            {
                //参数化类型
                ParameterizedType parameterType=(ParameterizedType) superClassType;
                
                //泛型参数的 Type 对象的数组
                Type[] parameters=parameterType.getActualTypeArguments();
                //返回实体类参数
                return (Class<T>)parameters[0];            
            }
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
        return null;
    }
}

 

转载于:https://www.cnblogs.com/temporary/p/7827408.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值