分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

Hibernate 泛型Dao实现

发布时间:2023-09-06 01:24责任编辑:郭大石关键词:Hibernate
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实现

原文地址:http://www.cnblogs.com/temporary/p/7827408.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved