关于org.hibernate.session的一些体会

本文介绍了一种在使用Hibernate框架时遇到的Session被关闭错误,通过调整代码逻辑解决了因事务嵌套导致的问题,并分享了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码如下:

BaseHibernateDAO类


ContractedBlock.gifExpandedBlockStart.gifCode
  1package com.test.DAO.impl;
  2
  3import java.io.Serializable;
  4import java.util.List;
  5
  6import org.hibernate.Session;
  7import org.hibernate.Transaction;
  8import org.hibernate.criterion.Example;
  9
 10import com.test.factory.HibernateSessionFactory;
 11
 12ExpandedBlockStart.gifContractedBlock.gifpublic abstract class BaseHibernateDAO {
 13    private Session session = null;
 14ExpandedSubBlockStart.gifContractedSubBlock.gif    protected Object get(Class clz,Serializable id){
 15        getSession();
 16        Object ret = null;
 17ExpandedSubBlockStart.gifContractedSubBlock.gif        try{
 18            ret = session.get(clz, id);
 19ExpandedSubBlockStart.gifContractedSubBlock.gif        }
catch(Exception e){
 20            e.printStackTrace();
 21            System.out.println("In BaseHibernateDAO function get");
 22ExpandedSubBlockStart.gifContractedSubBlock.gif        }
finally{
 23            closeSession();
 24        }

 25        return ret;
 26    }

 27ExpandedSubBlockStart.gifContractedSubBlock.gif    protected void add(Object item){
 28        getSession();
 29        Transaction tc = null;
 30ExpandedSubBlockStart.gifContractedSubBlock.gif        try{
 31            tc = session.beginTransaction();
 32            session.save(item);
 33            tc.commit();
 34ExpandedSubBlockStart.gifContractedSubBlock.gif        }
catch(Exception e){
 35ExpandedSubBlockStart.gifContractedSubBlock.gif            if(null!=tc){
 36                tc.rollback();
 37            }

 38            e.printStackTrace();
 39            System.out.println("In BaseHibernateDAO function add");
 40ExpandedSubBlockStart.gifContractedSubBlock.gif        }
finally{
 41            closeSession();
 42        }

 43    }

 44ExpandedSubBlockStart.gifContractedSubBlock.gif    protected void update(Object item){
 45        getSession();
 46        Transaction tc = null;
 47ExpandedSubBlockStart.gifContractedSubBlock.gif        try{
 48            tc = session.beginTransaction();
 49            session.update(item);
 50            tc.commit();
 51ExpandedSubBlockStart.gifContractedSubBlock.gif        }
catch(Exception e){
 52ExpandedSubBlockStart.gifContractedSubBlock.gif            if(null!=tc){
 53                tc.rollback();
 54            }

 55            e.printStackTrace();
 56            System.out.println("In BaseHibernateDAO function update");
 57ExpandedSubBlockStart.gifContractedSubBlock.gif        }
finally{
 58            closeSession();
 59        }

 60    }

 61ExpandedSubBlockStart.gifContractedSubBlock.gif    protected void delete(Class clz,Serializable id){
 62
 63        getSession();
 64        Transaction tc = null;       
 65ExpandedSubBlockStart.gifContractedSubBlock.gif        try{
 66            tc = session.beginTransaction();
 67            session.delete(this.get(clz,id));
 68            tc.commit();
 69ExpandedSubBlockStart.gifContractedSubBlock.gif        }
catch(Exception e){
 70ExpandedSubBlockStart.gifContractedSubBlock.gif            if(null!=tc){
 71                tc.rollback();
 72            }

 73            e.printStackTrace();
 74            System.out.println("In BaseHibernateDAO function delete");
 75ExpandedSubBlockStart.gifContractedSubBlock.gif        }
finally{
 76            closeSession();
 77        }

 78    }

 79ExpandedSubBlockStart.gifContractedSubBlock.gif    protected List search(Class clz,Object condition){
 80        List results = null;
 81ExpandedSubBlockStart.gifContractedSubBlock.gif        try{
 82            results = getSession()
 83                    .createCriteria(clz)
 84                    .add(Example.create(condition))
 85                    .list();
 86ExpandedSubBlockStart.gifContractedSubBlock.gif        }
catch(Exception e){
 87            e.printStackTrace();
 88            System.out.println("In BaseHibernateDAO function search");
 89ExpandedSubBlockStart.gifContractedSubBlock.gif        }
finally{
 90            closeSession();
 91        }

 92        return results;
 93    }

 94ExpandedSubBlockStart.gifContractedSubBlock.gif    protected Session getSession(){
 95        session = HibernateSessionFactory.getSession();
 96        return session;
 97    }

 98ExpandedSubBlockStart.gifContractedSubBlock.gif    protected void closeSession(){
 99        session = null;
100        HibernateSessionFactory.getSession().close();
101    }

102}

DoubleTest类


ContractedBlock.gifExpandedBlockStart.gifCode
 1package com.test.main;
 2
 3import com.test.DAO.impl.BaseHibernateDAO;
 4import com.test.entity.Avenue;
 5import com.test.entity.District;
 6
 7ExpandedBlockStart.gifContractedBlock.gifpublic class DoubleTest extends BaseHibernateDAO {
 8
 9ExpandedSubBlockStart.gifContractedSubBlock.gif    /** *//**
10     * @param args
11     */

12ExpandedSubBlockStart.gifContractedSubBlock.gif    public static void main(String[] args) {
13        // TODO Auto-generated method stub
14        new DoubleTest().TestDelAvenue();
15    }

16ExpandedSubBlockStart.gifContractedSubBlock.gif    public void TestAddDistrict(){
17        District district = new District();
18        district.setDname("徐汇");
19        super.add(district);
20    }

21ExpandedSubBlockStart.gifContractedSubBlock.gif    public void TestAddAvenues(){
22        District district = (District)super.get(District.class4);
23        Avenue a1 = new Avenue();
24        a1.setAname("和平路");
25        a1.setdistrict(district);
26        Avenue a2 = new Avenue();
27        a2.setAname("八一路");
28        a2.setdistrict(district);
29        Avenue a3 = new Avenue();
30        a3.setAname("五四大道");
31        a3.setdistrict(district);
32        super.add(a1);
33        super.add(a2);
34        super.add(a3);
35    }

36ExpandedSubBlockStart.gifContractedSubBlock.gif    public void TestDelAvenue(){
37        super.delete(Avenue.class18);
38    }

39}

在运行DoubleTest的时候,老出现org.hibernate.SessionException: Session is closed的错误

怎么想都不明白是什么原因,网上查了下,有的说是lazy要改成false,但改了之后还是一样

最后经过调试,终于发现错在事务的嵌套,delete函数中又调用了get函数,get函数返回的时候把session给关闭了

听我朋友说这个session是基于JDK的动态代理做出的事物管理的!基于一个session!

最后把程序修改了一下,终于成功了,附delete函数


ContractedBlock.gifExpandedBlockStart.gifCode
 1ExpandedBlockStart.gifContractedBlock.gifprotected void delete(Class clz,Serializable id){
 2        Object item = this.get(clz, id);
 3        getSession();
 4        Transaction tc = null;       
 5ExpandedSubBlockStart.gifContractedSubBlock.gif        try{
 6            tc = session.beginTransaction();
 7            session.delete(item);
 8            tc.commit();
 9ExpandedSubBlockStart.gifContractedSubBlock.gif        }
catch(Exception e){
10ExpandedSubBlockStart.gifContractedSubBlock.gif            if(null!=tc){
11                tc.rollback();
12            }

13            e.printStackTrace();
14            System.out.println("In BaseHibernateDAO function delete");
15ExpandedSubBlockStart.gifContractedSubBlock.gif        }
finally{
16            closeSession();
17        }

18
19}

转载于:https://www.cnblogs.com/jayhuecko/archive/2009/08/14/1546439.html

### Hibernate 中 `org.hibernate.dialect.Oracle12cDialect` 的使用说明及配置示例 #### 配置概述 为了使 Hibernate 能够正确识别和操作 Oracle 数据库中的对象,必须设置合适的 SQL 方言。对于 Oracle 12c 及以上版本,推荐使用的方言是 `org.hibernate.dialect.Oracle12cDialect`[^3]。 此方言不仅兼容标准的 SQL 功能,还支持 Oracle 12c 特有的功能,比如 **身份列(Identity Column)** 和其他高级特性。以下是具体的配置方式及其注意事项: --- #### XML 文件配置示例 (`hibernate.cfg.xml`) 如果项目基于传统的 XML 配置文件,则可以通过如下方式进行设置: ```xml <hibernate-configuration> <session-factory> <!-- 其他必要的配置 --> <property name="hibernate.dialect">org.hibernate.dialect.Oracle12cDialect</property> <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orclpdb1</property> <property name="hibernate.connection.username">your_username</property> <property name="hibernate.connection.password">your_password</property> <!-- 自动创建表结构 (可选) --> <property name="hibernate.hbm2ddl.auto">update</property> </session-factory> </hibernate-configuration> ``` 在此配置中,`hibernate.dialect` 属性被显式设置为 `org.hibernate.dialect.Oracle12cDialect`[^2]。 --- #### Java 基础配置示例 当采用程序化的方式初始化 Hibernate 会话工厂时,也可以动态指定方言。以下是一个简单的例子: ```java import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static SessionFactory sessionFactory; public static SessionFactory getSessionFactory() { if (sessionFactory == null) { Configuration configuration = new Configuration(); configuration.configure(); // 加载默认的 hibernate.cfg.xml // 显式设置方言和其他属性 configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle12cDialect"); configuration.setProperty("hibernate.connection.driver_class", "oracle.jdbc.driver.OracleDriver"); configuration.setProperty("hibernate.connection.url", "jdbc:oracle:thin:@localhost:1521:orclpdb1"); configuration.setProperty("hibernate.connection.username", "your_username"); configuration.setProperty("hibernate.connection.password", "your_password"); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()); sessionFactory = configuration.buildSessionFactory(builder.build()); } return sessionFactory; } } ``` 在这个实现中,通过编程接口设置了 `hibernate.dialect` 参数,并将其值设为 `org.hibernate.dialect.Oracle12cDialect`。 --- #### 注意事项 1. **驱动依赖**: 确保项目的类路径下存在正确的 JDBC 驱动包(如 `ojdbc8.jar`),以便能够连接到 Oracle 数据库实例。 2. **数据库权限**: 如果启用了自动 DDL 生成功能(例如 `hibernate.hbm2ddl.auto=update` 或 `create-drop`),则需要确保所用账户具有足够的权限来执行这些操作。 3. **测试环境验证**: 在开发阶段建议先运行一些基本查询语句以确认配置无误。例如打印生成的 SQL 语句用于调试目的: ```java System.out.println(org.hibernate.tool.schema.internal.SchemaCreatorImpl.ddlSQL(new org.hibernate.dialect.Oracle12cDialect())); ``` 4. **性能优化**: 根据实际需求调整缓存策略以及其他相关参数,从而提升应用的整体效率。 --- #### 总结 通过合理配置 `hibernate.dialect` 属性以及关联的连接细节,可以顺利集成 Hibernate 与 Oracle 12c 数据库之间的交互过程。选用恰当的方言有助于充分利用目标 RDBMS 提供的新特性和增强功能。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值