One, Opensessioin way to open or close things
Session session = Null;try {session = Hibernateutils.getsession (); session.begintransaction ();//Turn on transaction//todo: Various CRUD Operations Session.gettransaction (). commit (); Commit TRANSACTION} catch (Exception e) {e.printstacktrace (); Session.gettransaction (). rollback ();//Error Rollback} finally { Hibernateutils.closesession (session); Close Session}
Use this way to turn things on and off. But considering that our things are usually turned on or off at the service level. And the service inside calls the DAO layer method. Most of the cases. are called multiple methods. That is, a one-to-many call. To make sure that every time I start a business. It's all a session. That's a rough way to go.
two. Getcurrentsession Use things
1. Join the configuration using Currentsession
<property name= "Hibernate.current_session_context_class" >thread</property><!-- Place the session in Threadloacl--
2, replacing the GetSession method
To with for example with. The test user method is added to the Unit test class:
Code:
Every time I get a session. Use the Getcurrentsession method to get the session used by the current thread. Same, when you join log
Also use the above method to get the session, so that I can guarantee a series of CRUD operations, the use of a session.
Summary:
* opensession it is necessary to close the session, and currentsession is to close the session by itself after the end of the transaction .
*opsensession is not bound to the current thread, currentsession is bound to the current thread.
* Use currentsession the time needed in Hibernate Configuration file in the
Simple use of programming things in Hibernate