31st Day Lazy projection on the use of warm Yang-hibernate on JDBC (iv)

Source: Internet
Author: User
Tags object model

June 19, light rain. "in the apricot season every rain, grass pond frogs everywhere." Have about not come over midnight, idle knock Chess pieces Fall snuff. "

An object-oriented, inclusive personality, Gavin King, an Australian who is ignorant of SQL and database, creates a great space for imagination. Those awkward disadvantages---the difference in design concepts between OO and relational databases-"O/R impedance imbalance (O/R impedance mismatch)" etc.。 InAustralian peopleTransformation means, have been consciously or unconsciously eliminated.Hibernate, the transformation between object-oriented object model and relational database data structure has reached a peak. Okay, coder, yes.the session of Hibernate 's understanding is often surprising. Perhaps it can be said thatAustraliaFor peopleSessionExpression of their flexibility and flexibility. All of these, so that everyThe short life of the session between open and closehas been sublimated.

The session interface is responsible for performing crud operations on persisted objects (the task of crud is to complete the communication with the database, including many common SQL statements. )。 However, it is important to note that the session object is non-thread-safe.

1, DIY, packaging Hibernateutil class

in use to avoid resource consumption, a Hibernateutil class is typically manually encapsulated (without using spring management). The role of this class allows hibernate to load Config file config, create sessionfactory, and so on, and run only once.

Package Edu.eurasia.hibernate;import Org.hibernate.hibernateexception;import Org.hibernate.session;import org.hibernate.cfg.configuration;/** * Configures and provides access to hibernate sessions, tied to the current * thread O F execution. */public class Hibernateutil {/** * location of hibernate.cfg.xml file. Notice:location should be on the * Classpath as Hibernate uses #resourceAsStream style lookup for its * configuration fil E. That's place the config file with a Java package-the * default location is the default Java package.<br> * <b r> * Examples: <br> * <code>config_file_location = "/hibernate.conf.xml". */private static String config_file_location = "/hibernate.cfg.xml";/** holds a single instance of Session */private Stati C final ThreadLocal ThreadLocal = new ThreadLocal ()/** The single instance of Hibernate configuration */private static fi NAL Configuration cfg = new configuration ();/** the single instance of Hibernate sessionfactory */private statIC org.hibernate.SessionFactory sessionfactory;/** * Returns the ThreadLocal Session instance. Lazy Initialize the * <code>SessionFactory</code> if needed. * * @return Session * @throws hibernateexception */public static Session currentsession () throws Hibernateexception {Sess Ion Session = (session) Threadlocal.get (), if (session = = NULL | |!session.isopen ()) {if (sessionfactory = = null) {try {cfg . Configure (config_file_location); sessionfactory = Cfg.buildsessionfactory ();} catch (Exception e) {System.err.println ("%%%% Error Creating sessionfactory%%%%"); E.printstacktrace ();}} Session = (Sessionfactory! = null)? Sessionfactory.opensession (): Null;threadlocal.set (session);} return session;} /** * Close The single Hibernate session instance.  * * @throws hibernateexception */public static void CloseSession () throws Hibernateexception {Session session = (session) Threadlocal.get (); Threadlocal.set (null); if (session! = NULL) {Session.close ();}} /** * Default constructor. */privateHibernateutil () {}} 

2. Hibernate usage transactions

Hibernate provides a lightweight encapsulation of JDBC, which itself does not have transactional capabilities at design time. Hibernate encapsulates the underlying jdbctransaction or jtatransaction, and then sets the outer shell of the transaction and session, in fact, by delegating the underlying JDBC or JTA to handle the transaction function.

package Edu.eurasia.hibernate;import Java.util.iterator;import Org.hibernate.session;import org.hibernate.Transaction; public class Simpletransaction {public static void main (string[] args) {simpletransaction Simpletran = new Simpletransacti On (); Simpletran.tran ();}  Demonstrates the method used by the transaction public void Tran () {//Gets the current transaction session session = Hibernateutil.currentsession ();/declaration Transaction Transaction TX = Null;try {//HQL query statement string hql = "from UserInfo";//start of transaction tx = Session.begintransaction ();//intermediate operation of the transaction iterator it = Session.createque Ry (HQL). List (). iterator (); while (It.hasnext ()) {UserInfo UserInfo = (UserInfo) it.next (); System.out.println (Userinfo.getusername () + "" +userinfo.getpassword ());} Commit Transaction Tx.commit ();} catch (Exception ex) {if (tx! = null) {try {//ROLLBACK transaction tx.rollback ();} catch (Exception e) {e.printstacktrace ()}}} finally {/ /close Sessionsession.close ();}} 

3.MySQL database ,UserInfo class, mapping file UserInfo.hbm.xml and hibernate.cfg.xml configuration file See:

19th Day lazy projection on the use of warm Yang-hibernate on jdbc (i)

4. You also need to add a Slf4j-nop-1.6.2.jar file. The engineering structure is as follows:

Real It is often necessary to bind the current thread to the session. The general usage is to use threadlocal: to encapsulate the management of hibernate in the Hibernateutil class. The session was obtained through Opensession, and put it into the threadlocal variable. In this way the business logic simply takes the session of the current thread through the tool class. When finished, call the tool class CloseSession method to close the session, and the current thread's threadlocal variable is set to NULL. After the thread Cheng is guaranteed to be returned, the threadlocal is empty to prevent other threads from accessing this thread variable.

After that, Hibernate's Sessionfactory provides a new way to get the session getcurrentsession (gets the session bound to the current thread). Internal encapsulation via proxy, The resulting session is not only tied to the current thread, but also requires no manual switch. By default, the session closes automatically after the transaction commits.
at the end , after the introduction of spring, the creation of Sessionfactory is given to spring management. Spring also provides hibernatetemplate, Hibernatedaosupport such a package method. The user can no longer consider the management of the session, the transaction is turned off. Just configure the transaction.


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.