zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    Python PyInstaller安装和使用教程(搬来的,嘻嘻)
    python 注册码永久性方法
    网上搬来的常用工具
    Pycharm控制台窗口怎样可以显示不同程序的运行结果
    php时间:获取上一个月,本月天数,下一个月
    thinkphp5 --接口实例
    浅谈 PHP 与手机 APP 开发
    php 对象的调用和引入
    php 超全局变量(整理)
    php 全局变量和超全局变量
  • 原文地址:https://www.cnblogs.com/temporary/p/7827408.html
Copyright © 2011-2022 走看看