How to use hibernate sessions?

眉间皱痕 提交于 2019-12-23 18:32:23

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/5952074/how-to-use-hibernate-sessions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!