如何管理hibernate 的session?

03-08-16 zhengzhiyong
我在dao里用到hibernate操作数据库,在业务逻辑里的方法里,如增加,修改
,删除,SessionFactory在此业务逻辑里构建一个实例.我的session是在每个方法里都要如此 session = sessionFactory.openSession();
执行玩操作后,session.close().
但是如果在一个方法里调用另外一个方法,会提示session已被close.
一个bean,最好用一个session.
不知各位大虾是怎么用session的.用一个session是否行的通?
初学,谢了各位!

fahrenheit
2003-08-16 09:31
把session传过去

zhengzhiyong
2003-08-16 10:19
我笨:)
能详细点吗?

bruce
2003-08-23 05:32
你这样试试看行不行。 例如MethodA中有调methodB的代码: callB,你就可以这样写callB(session s),然后在B方法中直接用s.save() and so on.Good luck.成与不成,给个回复.

robbin
2003-08-23 10:56
用ThreadLocal管理session

http://hibernate.bluemars.net/42.html

zhengzhiyong
2003-08-23 11:49
谢谢各位,马上试一下!:)

不过现在有个新问题,请指教:
一个表Result,有两个主键,分别是customerId,setDate,用hibernate生成一个单独的主键类ResultPK.
现在我想查询表中所有customerId='0001'的记录,怎么写HQL语句???
我写的HQL语句:

//首先给主键表赋值
ResultPK resultPK = new ResultPK(); //结算主键表
resultPK.setCustomerId("0001");

//注:comp_id是Result类中ResultPK的实例
session.find("select result.comp_id from Result result where result.comp_id = "+resultPK+" ");

运行时出现错误:
net.sf.hibernate.QueryException: path expression ends in a composite value: result0_.comp_id [select result.comp_id from com.persistent.Result result where result.comp_id = com.persistent.ResultPK@11946c2[customerId=0001,setDate=<null>] ]

我不知道这样的语句怎么写?请大家帮帮忙!
先谢了。

xxmouse
2003-09-08 14:22
the idea is simple;
say, you have a composite-id in your Class Result, let assume that the name of it is "id" (and of course, id has two attributes: "customerId" and "setDate"), so we write the following sniplet to retrieve all the records in this table whose customerId='0001'.

select * from Result result where result.id.customerId='0001',

understand? just use double quote marks to enclose it in your HQL and you should be able to get it.
cheers