How to use hibernate sessions?
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 tim开发者_如何转开发e 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.
the sessions abstracts the db connections and it's not a good practice for your example to create a session for each iteration step, it is overhead. Instead open a new session or get the existing one with getCurrentSession().Moreover, It's still a good practice to use connection pools like C3P0 to manage database connections. To establish a connection to DB is expensive.
If your selects grab 10K records that are different between iterations, you might end up up with 50M objects in the Hibernate session when you use the same session for the entire operation.
You might want to at least flush and clear session after each iteration.
精彩评论