On the construction of Hibernate environment in Java EE (ii.)

Source: Internet
Author: User
Tags xml parser ibm developerworks

Starting today, we come together to learn about the hibernate framework, which is actually a highly encapsulated framework based on JDBC, Therefore, the efficiency of hibernate is not as high as that of JDBC, but hibernate is more efficient than JDBC, which is what enterprise-level development pursues. So at present, most enterprise development will not use JDBC. To work well, its prerequisite, first of all, we are familiar with the setting of hibernate environment.

Hibernate environment Setup Steps:

The first step: Get to Hibernate release package, can go to hibernate official online to download, or go to GitHub Direct search Hibernate,hibernate code is hosted on GitHub

: https://sourceforge.net/projects/hibernate/files/hibernate3/, official website: http://in.relation.to/hibernate-orm/. I got the release package here is Hibernate3 now updated to 4 version, no matter with 3 or 4 can be, but must unify, do not use both part 3.0 of the jar package, Also used 4.0 jar this will be a problem, to the late development of a series of problems, it is recommended to unify all the jar version, in fact, do not worry, you just need to download a complete final package, all the necessary jar inside. After downloading the final package, unzip the directory such as:


Hibernate includes a total of 23 jar packs, dazzling. This article will explain in detail the role of each jar package in hibernate, so that you can make your own choices in your application.

To download hibernate, for example 3.6.1 stable version, unzip, you can see a Hibernate3.jar and lib directory with 22 jar packages:

Hibernate3.jar:

Hibernate library, there is nothing to say, the jar package must be used
Cglib-asm.jar:

Cglib Library, Hibernate uses it to achieve the dynamic generation of PO bytecode, very core libraries, must use the JAR package
Dom4j.jar:
DOM4J is a Java XML API, similar to Jdom, used to read and write XML files. Dom4j is a very, very good Java XML API that features great performance, power, and extreme ease of use, as well as an open source software that can be found on SourceForge. The IBM Developerworks can find an article on the performance, functionality, and usability of the mainstream Java XML API, and DOM4J is excellent in that respect. I started using dom4j almost a year ago, until now. Now you can see that more and more Java software is using dom4j to read and write XML, especially to mention that even Sun's JAXM is using DOM4J. This is the jar package that must be used and hibernate uses it to read and write the configuration file.

Odmg.jar:
ODMG is an ORM specification, Hibernate implements the ODMG specification, which is a core library that must be used by the jar package.
Commons-collections.jar:

One of the Apache Commons packages contains some Apache-developed collection classes that are more powerful than java.util.*. The jar package that must be used.

Commons-beanutils.jar:
One of the Apache commons packages contains some Bean tool class classes. The jar package that must be used.
Commons-lang.jar:
One of the Apache Commons packages, containing some data type tool classes, is an extension of the java.lang.*. The jar package that must be used.
Commons-logging.jar:
One of the Apache Commons packages that contains the log functionality that must be used by the jar package. The package itself contains a simple Logger, but the function is very weak. In the run time it will first find log4j in Classpath, if there is, the use of log4j, if not, find JDK1.4 with the java.util.logging, if you can not find the simple Logger. Commons-logging.jar's appearance is a historical legacy of regret, originally Apache lobbied Sun log4j to join JDK1.4, but JDK1.4 project team is close to release JDK1.4 product time, so rejected Apache requirements, use their own Java . util.logging, this package has a far worse function than log4j, and the performance is general. Later, Apache developed the Commons-logging.jar to be compatible with two logger. Therefore, the log program written with Commons-logging.jar, the underlying Logger can be switched, you can choose log4j,java.util.logging or its own simple Logger. However, I still strongly recommend the use of log4j, because the log4j performance is very high, log output information time is almost equal to System.out, and processing a log on average only need 5us. You can find the log4j configuration file that hibernate has prepared for you in the SRC directory of hibernate, you just need to go to the Apache website to download log4j. Commons-logging.jar is also a required jar package.
The jar packages required for Hibernate are the ones above, and the rest are optional.
Ant.jar:

The ant compilation Tool's Jar package is used to compile the hibernate source code. If you are not ready to modify and compile Hibernate source code, then there is no use, optional jar package
Optional.jar:
An auxiliary package for Ant.

C3p0.jar:

C3PO is a database connection pool that hibernate can configure to use the C3PO connection pool. If you are going to use this connection pool, you will need this jar package.

Proxool.jar:

is also a connection pool, ibid.

Commons-pool.jar, Commons-dbcp.jar:

DBCP database Connection pool, Apache Jakarta organization developed, TOMCAT4 connection pool is also dbcp.

In fact, hibernate itself has implemented a very very simple database connection pool, plus the top 3, you can actually choose 4 different database connection pools on hibernate, choose which one to look at the personal preferences, but dbcp may be more general. In addition, if Hibernate is used in EJBs, be sure to use the connection pool of app server, not the above 4 connection pools, otherwise the container management transaction will not work.

Connector.jar:

JCA specification, this jar is required if you configure Hibernate as connector on the app server. But in fact, the General app server will definitely bring this package, so it's actually an extra package.

Jaas.jar:


Jaas is used for permission validation and is already included in the JDK1.4. So it's actually an extra bag.

Jcs.jar:

If you are going to use JCS in Hibernate, you must include it, otherwise you will not have to.

Jdbc2_0-stdext.jar:

JDBC2.0, the database connection pool will typically be used for the extension package. But the app server is always on, so it's redundant.

Jta.jar:

The JTA specification is required when Hibernate uses JTA, but the app server is always on, so it's redundant.

Junit.jar:

The JUnit package is required when you run Hibernate's own test code, otherwise it is not needed.

Xalan.jar, Xerces.jar, Xml-apis.jar:

Xerces is an XML parser, Xalan is a formatter, Xml-apis is actually JAXP. General app Server will bring, JDK1.4 also contains the parser, but not xerces, is crimson, inefficient, but hibernate with XML is just read configuration file, performance is not critical, so is redundant.

With a simple analysis and introduction to the 23 jar packs under Hibernate, I believe you should know how to choose the jar that is right for you to develop, but there are only 8 jars necessary for a general beginner to develop hibernate.

The 8 jars are: 1, the Hibernate3.jar,hibernate Library jar package must be 2, in your decompression directory has a Lib directory, the Lib directory has four folders, select the Require (required) folder of all 6 jars,

Then select all 1 jars in the JPA folder, a total of 8 jar packages.


Step two: Open Eclipse to create a new dynamic Web project, and create a new DTD folder under the project's root directory. Then in the final Package decompression folder has a Hibernate3.jar also is Hibernate core library with decompression software unzip it, extracted to hibernate directory to find two files ending in. DTD, copy them to the directory of the DTD file we just built. In fact, these two files are configured in Hibernate, respectively, the core configuration file, and the relational mapping file.



The third step is to put the 8 jars we have selected above into the Web-inf/lib directory in WebContent, and we need to put in a driver package that connects to the database, and I use the MySQL data driver package here. Remember to put in WebContent in the Web-inf/lib directory, do not build a folder and then add Bulide Path such in the future web development will be reported exceptions to the exception of the class, do not need to add bulide Path, Because this is a dynamic Web project, it is automatically added to the path.


Fourth step: Configure Hibernate's core profile hibernate.cfg.xml, create a new XML file in the SRC directory of the project, the SRC directory is hibernate default loading directory, remember when the new hibernate configuration file

Be sure not to take your own name, it only has a name hibernate.cfg.xml, do not write wrong, otherwise the environment is invalid.


Then open the Hibernate-configuration-3.0.dtd file under the DTD directory as follows:


Paste the selected code into Hibernate.cfg.xml, and then copy the selected URL


Then follow the Red Arrows on the graph:


Once the configuration is confirmed and the Hibernate configuration code hint can be played, we are already connected.


Finally, we can configure hibernate in the XML file through the code, but because many of the configured code is not familiar at all, we need to go to the instance in the copy document, noting that this code doesn't need to be remembered because it doesn't make much sense, so read the documentation. Where does the document look? In the unpacked folder of the release package has a documentation folder, and then there is a manual folder, open the folder, there is a ZH_CN Chinese API document, open the ZH_CN there is an HTML folder inside a number of HTML-formatted documents, Locate the Hibernate configuration column, and then copy all the contents of the


The final Hibernate.cfg.xml configuration code is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http://www.hibernate.org/ Dtd/hibernate-configuration-3.0.dtd ">Fifth Step Configuration table mapping file, hibernate mapping file is very important, you can use the map file to transform our Bean class into a table in the database, that is, we just have to build the Bean class, write the mapping file information, and configure the mapping file to the configuration file, The Hibernate API allows you to automate the creation of data tables, which is one of the ways to detect whether our hibernate environment is well built.

So we'll start by building a student class (Bean Class) object and a test class object tabletest. And first create an empty database named demo.



Then configure the mapping file next, remember to create a new XML file under the Bean package, the file name is student (lowercase of the Bean Class), Student.hbm.xml, Then open the Hibernate-mapping-3.0.dtd file under the DTD directory, then open the file, copy the contents of the header, and paste the contents into the Student.hbm.xml.




Then copy the above selected URL, as configured above


Finally, if the code hints are detected, the correlation is successful. Then the next is how to write the mapping file, I do not look for the API here, I give a format, the basic can follow this format to

Note: In the future when writing the mapping file must be corresponding to the Bean class to write, here for good-looking and easy to understand, I put student (Bean Class) and student.hbm.xml mapping files together to see.

Package Com.mikyou.bean;import Java.io.serializable;public Class Student implements serializable{/** * */private static Final long Serialversionuid = 1l;private long id;private string name;private int age;private string sex;public Student (Lon G ID, string name, int age, string sex) {super (); this.id = Id;this.name = Name;this.age = Age;this.sex = sex;} Public Student () {//TODO auto-generated constructor stub}public Long getId () {return ID;} public void SetId (Long id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public String Getsex () {return sex;} public void Setsex (String sex) {this.sex = sex;} public static long Getserialversionuid () {return serialversionuid;} @Overridepublic String toString () {return "Student [id=" + ID + ", name=" + name + ", age=" + Age + ", sex=" + Sex + "]";} }

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-mapping public     "-//hibernate/hibernate mapping DTD 3.0//en"    "Http://www.hibernate.org/dtd /hibernate-mapping-3.0.dtd ">    

The sixth step is to configure the mapping file that we have written to the Hibernate.cfg.xml configuration file, before introducing it, be sure to check that your mapping file and the attributes in the Bean class correspond, otherwise you will not be able to create the table automatically.

It is simple to put <mapping resource= "Com/mikyou/bean/student.hbm.xml"/> This line of code into the configuration file, Resource configuration is the path of the mapping file relative to the project engineering

The code for the final configuration file is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http://www.hibernate.org/ Dtd/hibernate-configuration-3.0.dtd ">
Seventh step, finally to the last step, write the table test class and insert a record through the code, and see if the data table is successful, the data is inserted successfully.

Package Com.mikyou.test;import Java.util.date;import Org.hibernate.sessionfactory;import org.hibernate.Transaction ; import Org.hibernate.cfg.configuration;import Org.hibernate.classic.session;import com.mikyou.bean.Student; public class Tabletest {public static void main (string[] args) {///1, creating Config object Configuration config=new configuration ();//2, Read the configuration file, Config.configure ();//Note There are a lot of overloaded methods here. The default is to load the profile in the SRC Directory///3, create a level cache based on profile information, Sessionfactory heavyweight objects, and do not create sessionfactory factory=config.buildsessionfactory frequently ( );//4, create session open sessions session=factory.opensession ();//5, open transaction transaction transaction= Session.begintransaction (); Student student=new Student (null, "Mikyou", 22, "male"), Session.save (Student);//6, transaction commit transaction.commit ();//7, Session Close}}

Test results:



Through the test results, we found that the automatic establishment of our table success also means that our hibernate environment to build success.









On the construction of Hibernate environment in Java EE (ii.)

Related Article

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.