且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用休眠会话?

更新时间:2022-10-24 08:41:17

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



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


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.