1. 程式人生 > >Hibernate 泛型Dao實現

Hibernate 泛型Dao實現

car warn sage common exc mes return eat pri

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

Hibernate 泛型Dao實現