如何使用休眠会话? [英] How to use hibernate sessions?

查看:92
本文介绍了如何使用休眠会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序结构如下:

在我的主要Java类中:

  for()//这将执行5000次---- LINE 1 
{
//在Database1上做选择(这将选择说10000行) - - LINE 2

//做一些计算(主要是字符串操作)---- LINE 3

调用function1()//这会对Database1做一些更新 - --- LINE 4
}

现在,我试图使用Hibernate访问Database1。我的问题是我应该如何使用hibernate会话来访问它。我应该什么时候开始会话,什么时候该结束?



如果我在for()循环之前启动它,我可以将同一会话传递给function1 ),因为它正在访问相同的数据库?或者一旦我选择了(LINE 1),我必须关闭它并在function1()中打开一个新的会话?
优化整体性能并尽量减少整体执行时间是我最关心的问题。


我是Hibernate的新手。因此,请原谅我,如果我要求一个非常愚蠢的怀疑。

解决方案

假设您想要所有更新为单个原子事务,您需要打开会话并在循环之前开始一个事务。然后,在循环之后,您需要提交事务并关闭会话。



如果每个更新都应该是它自己的原子事务,那么您应该只打开一个会话,然后为循环的每次迭代使用新的事务。


The structure of my program is as follows:

Inside my main java class:

for () // this will execute for say 5000 times ---- LINE 1
{
    // do select on Database1 (this will select say 10000 rows) ---- LINE 2

    // do some computations (mainly string operations) ---- LINE 3

    call function1() // this will do some update on Database1 ---- LINE 4
}

Now, I am trying to access Database1 using Hibernate. My question is how should I use hibernate session to access it. I am when should I start the session and when should I end it?

If I start it before the for() loop, can I pass the same session to function1() as it is accessing the same database? Or once I do the select (LINE 1) I have to close it and open a new session in function1()? Optimizing the overall performance and minimizing the overall execution time is my main concern.

I am new to Hibernate. Hence please pardon me if I am asking a very stupid doubt.

解决方案

Assuming you want all your updates to be a single atomic transaction, you'll need to open the Session and begin a transaction before the loop. Then, after the loop you'll want to commit the transaction and close the Session.

If each update should be its own atomic transaction, then you should still only open one Session, and then use a new transaction for each iteration of the loop.

这篇关于如何使用休眠会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆