为什么Hibernate Session第一次可以用,第二次就不可以呢?

问题描述

HibernateUtil代码packagecommon;importorg.hibernate.Session;importorg.hibernate.SessionFactory;importorg.hibernate.cfg.Configuration;publicclassHibernateUtil{privatestaticfinalSessionFactorysessionFactory=buildSessionFactory();privatestaticSessionFactorybuildSessionFactory(){try{returnnewConfiguration().configure().buildSessionFactory();}catch(Throwableex){System.err.println("InitialSessionFactorycreationfailed."+ex);thrownewExceptionInInitializerError(ex);}}publicstaticSessionFactorygetSessionFactory(){returnsessionFactory;}}

ExamInfoImpl代码packageservice.impl;importjava.io.UnsupportedEncodingException;importjava.util.List;importorg.hibernate.Query;importorg.hibernate.Session;importorm.exam_info;importservice.ExamInfo;importcommon.HibernateUtil;publicclassExamInfoImplextendsHibernateUtilimplementsExamInfo{/*(non-Javadoc)*@seeservice.ExamInfo#addExamInfo(orm.exam_info)*/publicvoidaddExamInfo(exam_infoexaminfo){Sessionss=HibernateUtil.getSessionFactory().openSession();ss.beginTransaction();ss.save(examinfo);ss.getTransaction().commit();}publicListgetExamInfo(){Sessionss=HibernateUtil.getSessionFactory().openSession();Listlist=null;Queryq=ss.createSQLQuery("select*fromSYS_EXAM_INFO").addEntity(exam_info.class);list=q.list();returnlist;}publicStringgetExamInfoById(Stringid){Sessionss=HibernateUtil.getSessionFactory().openSession();Listlist=null;StringBuildersb=newStringBuilder();Queryq=ss.createSQLQuery("select*fromSYS_EXAM_INFOwhereexam_eid="+id).addEntity(exam_info.class);list=q.list();if(list!=null){exam_infoobj=(exam_info)list.get(0);try{sb.append("[").append("{EXAM_EID:").append(obj.getEID()).append(",EXAM_ETIME:"").append(obj.getETIME()).append("",EXAM_MCOUNT:").append(obj.getMCOUNT()).append(",EXAM_MONEY:").append(obj.getMONEY()).append(",EXAM_NOWCOUNT:").append(obj.getNOWCOUNT()).append(",EXAM_OTHER:"").append(newString(obj.getOTHER().getBytes("iso-8859-1"),"gb2312")).append(""}").append("]");}catch(UnsupportedEncodingExceptione){e.printStackTrace();}}returnsb.toString();}}

代码逻辑上实现都没问题,问题是当我第一次调用ExamInfoImpl的getExamInfoById方法的时候第一次可以成功调用但是第二次再用的时候就提示org.hibernate.SessionException:Sessionisclosed!项目中就只用了Hibernate,希望高手能给出问题的原因和解决的办法谢谢

解决方案

解决方案二:
你代码应该没铁全,你找找看哪里把session关了,肯定就是不该关的时候关闭了session。。
解决方案三:
ExamInfoImpl类干吗要继承HibernateUtils类不懂个人建议最好一个数据库操作对应一个session操作,而且这里只给了个方法代码不全
解决方案四:
HibernateUtil类的问题在Hibernate给我们提供的一个sessionFactory类中,有如下的声明及使用:privatestaticfinalThreadLocal<Session>threadLocal=newThreadLocal<Session>();publicstaticvoidcloseSession()throwsHibernateException{Sessionsession=(Session)threadLocal.get();threadLocal.set(null);if(session!=null){session.close();}}从上面的代码应该可以看出.hibernate的session是取的当前线程中的.而你自定义类中。只是关闭了session.而并未对当前线程做处理。这样的话,会导致取到的session永远是关闭的.如果我的理解有误,请高手纠正
解决方案五:
[code]1111[/code]
解决方案六:
[java]111[/java]
解决方案七:
修改配置文件在一对多或多对多后面加lazy="false"
解决方案八:
dddd

解决方案九:
供参考packagecom.sideline.Hibernate;importorg.hibernate.HibernateException;importorg.hibernate.Session;importorg.hibernate.cfg.Configuration;/***ConfiguresandprovidesaccesstoHibernatesessions,tiedtothe*currentthreadofexecution.FollowstheThreadLocalSession*pattern,see{@linkhttp://hibernate.org/42.html}.*/publicclassSessionFactory{/***Locationofhibernate.cfg.xmlfile.*LocationshouldbeontheclasspathasHibernateuses*#resourceAsStreamstylelookupforitsconfigurationfile.*Thedefaultclasspathlocationofthehibernateconfigfileis*inthedefaultpackage.Use#setConfigFile()toupdate*thelocationoftheconfigurationfileforthecurrentsession.*/privatestaticStringCONFIG_FILE_LOCATION="/hibernate.cfg.xml";privatestaticfinalThreadLocal<Session>threadLocal=newThreadLocal<Session>();privatestaticConfigurationconfiguration=newConfiguration();privatestaticorg.hibernate.SessionFactorysessionFactory;privatestaticStringconfigFile=CONFIG_FILE_LOCATION;privateSessionFactory(){}/***ReturnstheThreadLocalSessioninstance.Lazyinitialize*the<code>SessionFactory</code>ifneeded.**@returnSession*@throwsHibernateException*/publicstaticSessiongetSession()throwsHibernateException{Sessionsession=(Session)threadLocal.get();if(session==null||!session.isOpen()){if(sessionFactory==null){rebuildSessionFactory();}session=(sessionFactory!=null)?sessionFactory.openSession():null;threadLocal.set(session);}returnsession;}/***Rebuildhibernatesessionfactory**/publicstaticvoidrebuildSessionFactory(){try{configuration.configure(configFile);sessionFactory=configuration.buildSessionFactory();}catch(Exceptione){System.err.println("%%%%ErrorCreatingSessionFactory%%%%");e.printStackTrace();}}/***Closethesinglehibernatesessioninstance.**@throwsHibernateException*/publicstaticvoidcloseSession()throwsHibernateException{Sessionsession=(Session)threadLocal.get();threadLocal.set(null);if(session!=null){session.close();}}/***returnsessionfactory**/publicstaticorg.hibernate.SessionFactorygetSessionFactory(){returnsessionFactory;}/***returnsessionfactory**sessionfactorywillberebuildedinthenextcall*/publicstaticvoidsetConfigFile(StringconfigFile){SessionFactory.configFile=configFile;sessionFactory=null;}/***returnhibernateconfiguration**/publicstaticConfigurationgetConfiguration(){returnconfiguration;}}

解决方案十:
有正解么。等。
解决方案十一:
每个方法都要关闭session,像这样的:publicListgetExamInfo(){Sessionss=HibernateUtil.getSessionFactory().openSession();Listlist=null;Queryq=ss.createSQLQuery("select*fromSYS_EXAM_INFO").addEntity(exam_info.class);list=q.list();ss.close();returnlist;}你把方法里面都加下试下看,看还会不会报错
解决方案十二:
修改Hibernate配制文件将配制文件中的lazy属性设置为"false"
解决方案十三:
引用11楼huai__ye的回复:

 修改Hibernate配制文件将配制文件中的lazy属性设置为"false"

??????????

时间: 2024-07-29 21:28:23

为什么Hibernate Session第一次可以用,第二次就不可以呢?的相关文章

spring-求解决No Hibernate Session bound to thread

问题描述 求解决No Hibernate Session bound to thread ssh项目在运行时控制台没有出错,但是页面出现 HTTP Status 500 - No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here怎么解决??? applicationContext.xml文件配置如下: <?xml version=&quo

session-Could not open Hibernate Session for transaction

问题描述 Could not open Hibernate Session for transaction ssh集成访问action时候报这个错误,数据库是oracle11g,数据库连接池用的c3p0,按照搜到的配置自动重连也没用.使用PLSQL可以连接到oracle spring配置文件关于数据库连接池和sessionFactory的内容如下: <bean id="sessionFactory" class="org.springframework.orm.hibe

Hibernage错误:Could not open Hibernate Session for transaction

今天在做SSH框架整合的时候碰到的这个问题,在测试service层的时候程序正常运行,但是添加Struts,在action层测试的时候提示了如下问题:Could not open Hibernate Session for transaction.大概意思就是数据库连接超时. 解决方法如下: 在spring的配置文件中添加如下配置 给sessionFactory的bean添加如下配置 <bean id="sessionFactory" class="org.spring

中文查询失败-hibernate session.createSQLQuery 模糊查询失败

问题描述 hibernate session.createSQLQuery 模糊查询失败 Hibernate: SELECT * from court where is_delete=0 and name like '%成成%' limit ? 将上面的SQL放到工具上面可以执行成功,但是hibernate查询不到数据. 如果我将高尔夫换成英文或者数字就可以查询成功,网上很多人都说是乱码照成的,但是我的SQL显示的不是乱码.请问有谁知道什么原因,并且如何解决. hibernate 版本4.3.5

javascript-html5 js和css3问题滑动第一次没有效果第二次才出来

问题描述 html5 js和css3问题滑动第一次没有效果第二次才出来 js加css3实现动画问题.. javascript函数css3动画html5 第一个:::: function slideList(){ var downY = 0; var step = 1/4; var nowIndex = 0; var nextorprevIndex = 0; $li.on('touchstart',function(ev){ var touch = ev.originalEvent.changed

mysql java 数据库-java连接MYSQL数据库第一次可以,第二次报错

问题描述 java连接MYSQL数据库第一次可以,第二次报错 做项目在做一个用户首次登陆输入手机号码,发送随机密码的功能模块,首次点击完全没问题,系统会发送短信(中国移动的短信机的原理是连接它的数据库,插入一条数据即可)问题就出在连接数据库的问题上,再次发送,则后台报错ResultSet is from UPDATE. No Data.. 报错信息如下 严重: Exception occurred during processing request: ResultSet is from UPDA

c# winform-VS2013下C#程序运行第一次错误,第二次正常

问题描述 VS2013下C#程序运行第一次错误,第二次正常 编译成功后的程序,第一次启动时会弹出窗口"The operation could not be completed.另一个程序正在使用此文件,进程无法访问."点击确定关闭弹出窗口后,再次点击vs的启动,就可以正常运行程序.这是什么错误,是什么原因造成的?谢谢! 解决方案 你再试试看第三次第四次呢?重启再试试呢. The operation could not be completed.这个提示和你的程序无关,这是VS的提示.

scanf_s while循环-VS2015,用scanf_s警告,循环输入的第一次正常,第二次出错。求指点

问题描述 VS2015,用scanf_s警告,循环输入的第一次正常,第二次出错.求指点 刚接触VS2015,在.net3.5 x86下写了个c程序. #include int main(void) { const int WEEK = 7; int days, weeks,left; printf("Please enter the numbers of days.n"); printf("Enter 0 to quit.n"); scanf_s("%d&

andriod 编译 驱动-andriod编译后烧写到机子上第一次正常,第二次无法进入系统

问题描述 andriod编译后烧写到机子上第一次正常,第二次无法进入系统 自己编译的andriod固件,烧写到机器里,第一次可以正常启动系统,使用均正常,但是在关机时,弹出的消息框会抖动,变窄.关机后再次开机无法进入系统,但是背光是亮的,也有可能是进入系统但是lcd屏幕没有显示.具体原因还不知道,有没有大神知道这个问题该如何解决?或者该从什么方向入手解决?