Simple use of programming things in Hibernate

Source: Internet
Author: User


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.