Follow up the entire process of the hibernate experiment project.

Source: Internet
Author: User

Let's talk about the experiment project environment:

Hibernate project jar package

Hibernate-3.2.6.ga.jar

Proxool-0.9.0RC3.jar

Jdk1.6

MySQL database

Project Introduction

Hibernate uses the persistent layer of the database, in which the connection pool proxool is used to manage the session of hibernate.

Project Construction

1. Create a hibernatedemo Project

2. Add hibernate. cfg. xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

3. Add proxool. xml

<? XML version = "1.0" encoding = "UTF-8"?> <Something-else-entirely> <proxool> <! -- The Connection Pool name must be consistent with the proxool. pool_alias parameter set by hibernate --> <alias> proxoolpool </alias> <! -- Proxool can only manage connections generated by itself --> <driver-URL> JDBC: mysql: // 127.0.0.1: 3306/web3_plus? Characterencoding = UTF-8 </driver-URL> <driver-class> COM. mySQL. JDBC. driver </driver-class> <driver-Properties> <property name = "user" value = "root"/> <property name = "password" value = "12344"/> </driver-Properties> <! -- The proxool automatically detects the time interval (in milliseconds) of each connection status, and immediately recycles the idle connection, destroy timeout --> 

The basic environment of hibernate has been configured.

4. Create the sessionfactory of Hibernate and initialize hibernate.

/** File name: COM. qisentech. data. hibernate. hibernatesessionfactory. java * creation date: 0:24:58 * Creator: qsyang */package COM. qisentech. data. hibernate; import Java. util. hashmap; import Java. util. map; import Org. hibernate. session; import Org. hibernate. sessionfactory; import Org. hibernate. cfg. configuration;/***** @ author qsyang */public class hibernatesessionfactory {Private Static Boolean inited = False; Private Static sessionfactory factory = NULL; Private Static configuration CFG = NULL;/*** initialize */public static synchronized void Init () {If (! Inited) {try {CFG = new configuration (); cfg. configure ("hibernate. cfg. XML "); factory = cfg. buildsessionfactory (); inited = true;} catch (exception ex) {log. error ("initialization hibernate error", ex); throw new runtimeexception (Ex) ;}} else {Throw new Java. lang. illegalstateexception ("hibernatesessionfactory already initialized") ;}} public static session opensession () {return factory. opensession ();} public static void destory () {factory. close ();}}

Well, we need to call the init method to initialize hibernatesessionfactory before the system runs.

Of course, it can also be created during testing, but it is time-consuming to create sessionfactory.

5. Create an object for testing.

Tfunction and ttoolsbox (one-to-many relationship)

/** File name: COM. qisentech. webplus. entity. tfunction. java * creation date: 15:40:01 * Creator: qsyang */package COM. qisentech. webplus. entity; import Java. util. list;/***** <p> title: </P> ** <p> description: </P> ** @ author qsyang * @ version 1.0 */public class tfunction {private int ID; private string name; private string IMG; private int sort; private Boolean issystem; private list <ttoolsbox> toolsboxlist;/*** @ return the ID */Public int GETID () {return ID ;} /*** @ Param ID the ID to set */Public void setid (int id) {This. id = ID;}/*** @ return the name */Public String getname () {return name ;} /*** @ Param name the name to set */Public void setname (string name) {This. name = Name;}/*** @ return the IMG */Public String getimg () {return IMG ;} /*** @ Param IMG the IMG to set */Public void setimg (string IMG) {This. IMG = IMG;}/*** @ return the sort */Public int getsort () {return sort ;} /*** @ Param sort the sort to set */Public void setsort (INT sort) {This. sort = sort;}/*** @ return the issystem */Public Boolean isissystem () {return issystem ;} /*** @ Param issystem the issystem to set */Public void setissystem (Boolean issystem) {This. issystem = issystem;}/*** @ return the toolsboxlist */public list <ttoolsbox> gettoolsboxlist () {return toolsboxlist ;} /*** @ Param toolsboxlist the toolsboxlist to set */Public void settoolsboxlist (list <ttoolsbox> toolsboxlist) {This. toolsboxlist = toolsboxlist ;}}

/** File name: COM. qisentech. webplus. entity. ttoolsbox. java * creation date: 16:53:25 * Creator: qsyang */package COM. qisentech. webplus. entity;/*** <p> title: </P> ** <p> description: </P> ** @ author qsyang * @ version 1.0 */public class ttoolsbox {private int ID; private string name; private string implclass; private int functionid; private string IMG; private int sort; private string URL; private Boolean isvalid; private string target;/*** @ return the ID */Public int GETID () {return ID ;} /*** @ Param ID the ID to set */Public void setid (int id) {This. id = ID;}/*** @ return the name */Public String getname () {return name ;} /*** @ Param name the name to set */Public void setname (string name) {This. name = Name;}/*** @ return the implclass */Public String getimplclass () {return implclass ;} /*** @ Param implclass the implclass to set */Public void setimplclass (string implclass) {This. implclass = implclass;}/*** @ return the IMG */Public String getimg () {return IMG ;} /*** @ Param IMG the IMG to set */Public void setimg (string IMG) {This. IMG = IMG;}/*** @ return the sort */Public int getsort () {return sort ;} /*** @ Param sort the sort to set */Public void setsort (INT sort) {This. sort = sort;}/*** @ return the URL */Public String geturl () {return URL ;} /*** @ Param URL the URL to set */Public void seturl (string URL) {This. url = URL;}/*** @ return the target */Public String gettarget () {return target ;} /*** @ Param target the target to set */Public void settarget (string target) {this.tar get = target ;} /*** @ return the isvalid */Public Boolean isisvalid () {return isvalid;}/*** @ Param isvalid the isvalid to set */Public void setisvalid (Boolean isvalid) {This. isvalid = isvalid;}/*** @ return the functionid */Public int getfunctionid () {return functionid ;} /*** @ Param functionid the functionid to set */Public void setfunctionid (INT functionid) {This. functionid = functionid ;}}

After the object is created, you need to create the corresponding object configuration ing file, mainly the ing between object attributes and database table fields.

T. function. HBM. xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

T. ttoolsbox. HBM. xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

Well, the configuration file has been written. You need to add the configuration file to hibernate. cfg. XML for ing.

<mapping resource="com/qisentech/webplus/entity/T.Function.hbm.xml"/><mapping resource="com/qisentech/webplus/entity/T.TToolsBox.hbm.xml"/>

6. Start the first object acquisition test.

Database t_function table data is as follows:

1 System Management Box_title_xtgl.gif 10 1
2 Basic functions Box_title_jlgl.gif 20 1
3 Related Components Box_title_xgzj.gif 30 1

The data in the t_toolsbox table is as follows:

1 Personal Information Null Box_xgmm.gif 50 Main. jsp 1 _ Self 1
2 Personnel Management Null Box_idsgl.gif 50 Index. jsp 1 _ Self 2
3 Department management Null Box_yxsz.gif 50 Test. jsp 1 _ Blank 3

Test the get method of a session:

Session session = null;try {    session = HibernateSessionFactory.openSession();    Object obj = session.get(TFunction.class, id);    return obj == null ? null : (TFunction) obj;} catch (HibernateException ex) {    throw ex;}finally{    session.close();}

Test the load method of the session:

Session session = null;try {    session = HibernateSessionFactory.openSession();    Object obj = session.load(TFunction.class, id);    return (TFunction) obj;} catch (HibernateException ex) {    throw ex;}finally{    session.close();}

Episode: What is the difference between hibernate get and load?

1. Compare the returned results:

The Org. hibernate. objectnotfoundexception exception will be thrown if the load method cannot be retrieved.

If the get method cannot be retrieved, null is returned.

2. Comparison of the retrieval execution mechanism:

The get method and find method are both retrieved directly from the database, while the execution of the load method is complicated. First, check whether the session persistent context has a cache, if yes, the system returns the result directly. If no result is returned, the system determines whether the result is lazy. If the result is not directly accessed to the database for retrieval, the system queries the record and returns the result. If the result is lazy, a proxy object needs to be created, the initialized attribute of the object is false, and the target attribute is null. when accessing the properties of the obtained proxy object, the database is retrieved. If a record is found, the object of the record is copied to the target of the proxy object, and initialized = true. If it cannot be found, an exception is thrown.

Summary

In short, there is a fundamental difference between get and load. In a word, Hibernate considers the load method to exist in the database and can safely use the agent to delay loading, if a problem is found during use, only an exception can be thrown. For the get method, Hibernate must obtain the actual data; otherwise, null is returned.

There are still many things to explore about hibernate. I will continue to explain this to you. Let's study it together!

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.