Hibernate Development Guide

Source: Internet
Author: User
Tags xslt processor tld
The content is included, but there are many images in this article. It is best to see the version with the image:
Http://bsd.huangdong.com/dev/hibernate/startup/startup.html

Preface
Hibernate is becoming more and more mature as an excellent database persistence layer tool that has been widely used. This article focuses on developers who use hibernate. This chapter describes the initial settings of the development environment Used in the hibernate Development Guide, A simple example is used to show that hibernate is running normally.

The main tools used in this article are:

JDK: JDK 1.4.2
Development and Integration Environment: Eclipse 2.1.2
Hibernate 2.1
Database: Oracle 9i
Eclipse plug-in of hibernate: tanghan plugin
Please first check whether the software has been installed on your machine. For databases, it is only because Oracle has been installed on my machine that there will be no big difference in using other databases. My example also uses a Struts framework, because I think struts is a very good choice in the Web application framework, coupled with the database access layer hibernate, matching the two can achieve better results. To use struts, make sure that you have installed the following software:
Web Application Server: Tomcat 4.x
Struts 1.1 package
Eclipse's J2EE integration plug-in: myeclipse 2.7rc1 and later versions (struts support is available in 2.7)
If you do not want to use the commercial plug-in myeclipse, you can also use lomboz and easystruts to replace its functions. The specific software installation and plug-in installation are not described here. The following describes the configurations after installation.

Software Configuration
Let's first configure the database and write down the information required during database development.

Oracle-related configuration parameters
I have created a separate user in Oracle: HD and set its password to ABC. Allocate the corresponding database space for the user, and detailed configuration methods and information will not be described. In short, You need to obtain information similar to the following for development:

Machine address: hdibm (because localhost and 127.0.0.1 can be used on the local machine, if another machine uses the IP address of this machine)
Listening port of Oracle: 1521
Database instance name: hdorc
Access Username: HD
Access Password: ABC
It should be noted that at least the connect role should be assigned to HD users. In addition, the tablespace used by the table is allocated with sufficient or unlimited size limit. Otherwise, problems will occur during development. In addition, you need to download the latest JDBC package from the installed oracle or Oracle website. It has two packages, one of which is the JDK-related driver, the other is the multi-language support package (here we do not use the OCI driver, use the thin driver ). Because the jdk I use is 1.4, I use ojdbc14.jar for the driver package. The multi-language support package used by jdk1.4 is the same as that used by jdk1.2, Which is nls_charset12.jar.

In the database, we create tablesProgramDevelopment. Taking a simple user management as an example, we first create a simple user table (sysuser ):

Table Name: sysuser
User ID: userid (vchar: 32)
Username: username (vchar: 20)
User Password: userpasword (vchar: 20)
Last Logon Time: lastlogin (date)
You can also use this SQL statement to create a table:
Create Table "HD". "sysuser" ("userid" varchar2 (32) not null,
"Username" varchar2 (20) not null, "userpasword" varchar2 (20)
Not null, "lastlogin" date, primary key ("userid "),
Unique ("username "))
Tablespace "users"

Tomcat installation
The installation of Tomcat is very simple. download the relevant installation package from the Tomcat website and find the relevant directory. After installing Tomcat, you need to write down the following information:

Tomcat installation directory
Tomcat listening port (8080 by default)

Configure the plug-in tanghan plugin for hibernate for eclipse
When using this plug-in for the first time, many people may not be able to start using this plug-in, primarily because they do not know where to use it. First, open the two views provided by this plug-in: Database Access view and database data view. Select the two views from the window> display View> others on the menu:

Open the database access view, and we will configure the Oracle driver. Right click Oracle thin driver> modify driver information:

Here:

Driver name: Oracle thin driver
Driver package name: browse and select your ojdbc14.jar File
Driver: Oracle. JDBC. Driver. oracledriver
Driver Prefix: JDBC: oracle: thin: <username >@< password> // <Server> [: <1521>]/<database_name> (here is the latest URL writing method. For more information, see the URL description of the Oracle driver)
After configuring the driver, we will add a database connection:

Here:

Database connection name: hdtestdb
Driver name: Oracle thin Driver (created above)
Driver: Oracle. JDBC. Driver. oracledriver
Database Connection: jdb C: oracle: thin: HD @ ABC // hdibm: 1521/hdorc
User name: HD
Password: ABC
Next we try to connect to the database:

Select shemas, select HD from the drop-down list, and click OK. If you can see the select shemas dialog box, it means that your database configuration is fine. We can see the table and table structure in the database access View:

Configure myeclipse
Download the latest myeclipse trial version and Struts-related TLD and lib packages from the myeclipse website. After installing myeclipse, configure tomcat. You can configure the relevant Tomcat paths:

It should be noted that Tomcat must use a JDK instead of a JRE. In the tomcat configuration tree, you can select a JDK for Tomcat startup:

Next, we will unbind the struts package downloaded from the website to the file system (you can also manually split the lib and TLD in the Struts 1.1 package), and configure the related packages of Struts 1.1 in myeclipse:

After completing these configurations, we can create a simple project.

Create an initial struts Project
We first set up a project to prepare for subsequent in-depth development. This project is a simple framework that imports Tomcat deployment support and establishes a library path with Struts and hibernate.

Create a web application project
First, use the Wizard to create a web module project:

Enter the related information of the web project:

Enter one by one as shown in the figure. Click to complete project creation.

Add Tomcat deployment support for the project
Next, add Tomcat deployment support for the project:

In the displayed dialog box, click Add and select Tomcat 4 from the drop-down list:

Add struts support for Web Applications
Add struts support for the project:

In the displayed dialog box, press Enter:

In this way, Struts support is added to the web application project. In this step, the struts support package and the TLD file (TAG lib description file) are automatically added to the project ). Then we can see:

Add hibernate support for Web Applications
There are a large number of jar files in hibernate. We do not recommend that you add them all. The following are the jar packages you must add (these packages except hibernate2.jar are all in the Lib subdirectory under the root ):

Hibernate2.jar: the core library of hibernate.
Cglib2.jar: the Library required by hibernate to dynamically generate Po bytecode.
Commons-collections.jar: Apache Commons provides a better collection class than Java. util.
Commons-lang.jar: Apache Commons provides the ability to extend java. Lang.
Commons-logging.jar: A common log interface tool provided by Apache commons. It uses the simple logger sequence of log4j, JDK java. util. logging, and commons-logging to find available log APIs.
Dom4j. jar: a Java interface for accessing XML. hibernate uses this package to complete XML operations.
ODMG. jar: ODMG Is An ORM specification. hibernate uses this package to implement the ODMG specification.
Xalan. jar, xerces. jar and xml-apis.jar: XSLT processor, Sax parsing, standard jaxp api package, all for XML processing. (Most application servers carry these three packages)
The following package can be added based on your application's situation. It is up to you:
C3p0. jar: package used by the C3PO database connection pool.
Commons-dbcp.jar and commons-pool.jar: the package used by the database connection pool named DBCP provided by Apache commons.
Jboss-cache.jar, concurrent. jar, jboss-common.jar, jboss-jmx.jar, jboss-system.jar: the package used by treecache, which implements a cache that can be clustered.
Connector. jar: Standard jca api package. Most application servers have them.
(*) Ehcache. jar: ehcache cache package. hibernate uses this package by default to complete the cache function.
JAAS. jar: Standard jaas api package. Most application servers also carry this package, which is used by JCA. (JDK 1.4 also contains this package)
JCs. jar: JCs cache package.
Jdbc2_0-stdext.jar: Standard JDBC 2.0 API extension package. Most application servers also include this package.
Swarmcache. jar and jgroups. jar: packages used by swarmcache to replicate distributed cache. It uses javagroups for group communication and is suitable for database application cache in cluster environments.
(*) JTA. jar: Standard jta api package. Most application servers also carry this package.
Log4j. jar: log4 package. log4j is a good choice among logger tools.
Oscache. jar: Oscache package provided by opensymphony for database cache.
Proxool. jar: The proxool JDBC database connection pool package.
Some other packages are not used at the runtime. They are attached here for better understanding:
Ant. jar: the ant core package used to compile hibernat.
JUnit. jar: The JUnit testing framework package, which is tested during compilation.Code Used for testing.
Optional. jar: Auxiliary package used by ant, including some additional tasks.
The method to add the package is very simple, use the resource manager to drag the JAR file into the lib directory of the WEB-INF under the web directory. Myeclipse automatically adds all jar files in this directory to the project's compiled classpath. Note: In addition to the required packages, add (*) packages to the project. Because Tomcat is used, the XML package in the required package can also be left empty. For example:

Add JDBC driver package for Web Applications
Add the prepared Oracle driver package to the web project. These two files:

Nls_charset12.jar
Ojdbc14.jar
Is the list of all packages configured to the end. Please check them one by one:

Configure the hibernate configuration file
Configure the hibernate database connection Configuration
The database connection configuration is very simple. Create an XML file named hibernate. cfg. xml under the src directory of the project. The content of this file is:

<? XML version = '1. 0' encoding = 'utf-8'?>
<! Doctype hibernate-configuration public "-// hibernate/hibernate configuration DTD // en" "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">

<Hibernate-configuration>

<Session-factory>

<Property name = "dialect"> net. SF. hibernate. dialect. oracle9dialect </property>
<Property name = "connection. driver_class"> oracle. JDBC. Driver. oracledriver </property>
<Property name = "connection. username"> HD </property>
<Property name = "connection. Password"> ABC </property>
<Property name = "connection. url"> JDBC: oracle: thin: @ localhost: 1521: hdorc </property>

<Property name = "connection. Pool. Size"> 1 </property>
<Property name = "statement_cache.size"> 25 </property>
<Property name = "JDBC. fetch_size"> 50 </property>
<Property name = "JDBC. batch_size"> 30 </property>

<Property name = "show_ SQL"> true </property>

<! -- Mapping Files -->
<Mapping Resource = "com/huangdong/demo/Dao/sysuser. HBM. xml"/>

</Session-factory>

</Hibernate-configuration>
Each property element here is described as follows:

Dialect: Compared with oracle9
Connection. driver_class: JDBC Driver Class Name of Oracle
Connection. Username: User Name for accessing the Oracle database
Connection. Password: Oracle Database Access Password
Connection. url: Oracle Database Access URL
Connection. Pool. Size: size of the Database Connection Pool
Statement_cache.size: JDBC Statement buffer size
JDBC. fetch_size: set the number of records retrieved from the database each time the JDBC Statement reads data.
JDBC. batch_size: Specifies the batch size for batch deletion, batch update, and batch insertion of databases.
Show_ SQL: Set whether to display SQL statements submitted to the database on the console. It is useful for development and debugging.
The proposed mapping resource is a list of the ing files in the database tables. We will map the sysuser table below, so we have added it now. This XML will be placed in the com. huangdong. Demo. Dao package, so we need to write the path during load.

Configure hibernate table ing
Select the sysuser table in Database Access view, and select generate HBM file from the menu:

In the wizard dialog box, enter the following information:

After you press the "done" button, the sysuser class and sysuser. HB. xml files are generated in the com. huangdong. Demo. Dao package.

Because it is inconvenient to use Java. util. Date in Java, I changed the ing Java attribute of lastlogin to calendar ar.

This is the modified sysuser. HBM. xml file:

<? XML version = "1.0" encoding = "UTF-8"?>
<! Doctype hibernate-mapping public "-// hibernate/hibernate mapping DTD 2.0 // en" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<Hibernate-mapping>
<Class name = "com. huangdong. Demo. Dao. sysuser" table = "sysuser">
<ID column = "userid" length = "32" name = "userid" type = "string">
<Generator class = "UUID. Hex"/>
</ID>
<Property column = "username" length = "20" name = "username" not-null = "true" type = "string" unique = "true"/>
<Property column = "userpasword" length = "20" name = "userpasword" not-null = "true" type = "string"/>
<Property column = "lastlogin" length = "7" name = "lastlogin" type = "calendar"/>
</Class>
</Hibernate-mapping>
This is the modified sysuser. Java file:

Package com. huangdong. Demo. Dao;

Import java. Io. serializable;
Import org. Apache. commons. Lang. Builder. equalsbuilder;
Import org. Apache. commons. Lang. Builder. hashcodebuilder;
Import org. Apache. commons. Lang. Builder. tostringbuilder;

/** @ Author hibernate codegenerator */
Public class sysuser implements serializable {

/** Identifier Field */
Private string userid;

/** Persistent field */
Private string username;

/** Persistent field */
Private string userpasword;

/** Nullable persistent field */
Private java. util. Calendar lastlogin;

/** Full constructor */
Public sysuser (Java. Lang. String username, java. Lang. String userpasword, java. util. Calendar lastlogin ){
This. Username = username;
This. userpasword = userpasword;
This. lastlogin = lastlogin;
}

/** Default constructor */
Public sysuser (){
}

/** Minimal constructor */
Public sysuser (Java. Lang. String username, java. Lang. String userpasword ){
This. Username = username;
This. userpasword = userpasword;
}

Public java. Lang. String getuserid (){
Return this. userid;
}

Public void setuserid (Java. Lang. String userid ){
This. userid = userid;
}

Public java. Lang. String GetUserName (){
Return this. Username;
}

Public void setusername (Java. Lang. String username ){
This. Username = username;
}

Public java. Lang. String getuserpasword (){
Return this. userpasword;
}

Public void setuserpasword (Java. Lang. String userpasword ){
This. userpasword = userpasword;
}

Public java. util. Calendar getlastlogin (){
Return this. lastlogin;
}

Public void setlastlogin (Java. util. Calendar lastlogin ){
This. lastlogin = lastlogin;
}

Public String tostring (){
Return new tostringbuilder (this)
. Append ("userid", getuserid ())
. Tostring ();
}

Public Boolean equals (object other ){
If (! (Other instanceof sysuser) return false;
Sysuser castother = (sysuser) Other;
Return new equalsbuilder ()
. Append (this. getuserid (), castother. getuserid ())
. Isequals ();
}

Public int hashcode (){
Return new hashcodebuilder ()
. Append (getuserid ())
. Tohashcode ();
}

}
Create a test Servlet
Create a servlet framework
The new servlet wizard is used to create a test servlet, which is the parameters and options entered when the servlet is created:

In the next XML wizard dialog box, clear the "test system function servlet" of the display name and description, as shown in:

In this way, an initial servlet framework is established.

Write database connection Retrieval Class
We compile a separate class to obtain the database connection Session from sessionfactory. This class is called hibernateutil. We put it in the com. huangdong. Demo. util package. The specific code is as follows:

Package com. huangdong. Demo. util;

Import net. SF. hibernate. hibernateexception;
Import net. SF. hibernate. Session;
Import net. SF. hibernate. sessionfactory;
Import net. SF. hibernate. cfg. configuration;

Public class hibernateutil {

Private Static final sessionfactory;

Static {
Try {
Sessionfactory =
New configuration (). Configure (). buildsessionfactory ();
} Catch (hibernateexception ex ){
Throw new runtimeexception (
"Exception building sessionfactory:" + ex. getmessage (),
Ex );
}
}

Public static final threadlocal session = new threadlocal ();

Public static session currentsession () throws hibernateexception {
Session S = (Session) Session. Get ();
// Open a new session, if this thread has none yet
If (S = NULL ){
S = sessionfactory. opensession ();
Session. set (s );
}
Return S;
}

Public static void closesession () throws hibernateexception {
Session S = (Session) Session. Get ();
Session. Set (null );
If (s! = NULL)
S. Close ();
}
}
We can use the currentsession method to obtain the database connection. If there is an available session in the system, it will be used back. If it is not, a new session will be created. After the session operation is complete, the operator needs to use the closesession method to release the used session.

Create a test Bean
Next, we will build a Java Bean for testhibernate, mainly adding some hibernate testing methods. The following is the information about the establishment of this class:

We add a method for adding data to the database for this class:

Public Boolean testadd (){
Try {
Session session = hibernateutil. currentsession ();
Transaction Tx = session. begintransaction ();
Sysuser user = new sysuser ();
User. setusername (" ");
User. setuserpasword ("uhkuhkqepdwqi ");
User. setlastlogin (calendar. getinstance ());
Session. Save (User );
TX. Commit ();
Hibernateutil. closesession ();
} Catch (hibernateexception e ){
E. printstacktrace ();
Return false;
}
Return true;
}
I was surprised when I wrote this code for the first time. I always felt that I should write more, but this is the case. We added a record to the database after just a few words.

Call the testadd method in Servlet
This is simple. You can change the doget method of the testservlet. Java class, initialize the testhibernate class, and call the testadd method:

Public void doget (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {

Response. setcontenttype ("text/html; charset = GBK ");
Printwriter out = response. getwriter ();
Out. println (
"<! Doctype HTML public \ "-// W3C // dtd html 4.01 transitional // en \"> ");
Out. println ("<HTML> ");
Out. println ("Out. println ("<body> ");

// Call test add
Testhibernate test = new testhibernate ();
Out. println ("testadd:" + test. testadd () + "<p> ");

Out. println ("</body> ");
Out. println ("Out. Flush ();
Out. Close ();
}
If the testadd method is successfully executed, true is returned on the page. Otherwise, false is returned. Let's test it.

Test our first servlet-based hibernate Application
Start Tomcat
If Tomcat deployment has been configured according to this article, there will be no problems here, and the operation will go to the debugging view of Eclipse:

All threads are started in the debug view, and "Starting coyote HTTP/1.1 on port 8080" is displayed in the console window. This indicates that Tomcat is started successfully and listening to port 8080, for example:

Open your browser and enter:

HTTP: /localhost: 8080/demo/servlet/testservlet
If the returned page is shown in, the database is updated successfully:

At the same time, we can see the hibernate log output in the eclipse console, explaining the details of its work:

15:10:37 net. SF. hibernate. cfg. Environment <clinit>
Information: hibernate 2.1.1
15:10:37 net. SF. hibernate. cfg. Environment <clinit>
Information: hibernate. properties not found
15:10:37 net. SF. hibernate. cfg. Environment <clinit>
Information: Using cglib reflection Optimizer
15:10:37 net. SF. hibernate. cfg. Configuration configure
Information: Tracing ing from resource:/hibernate. cfg. xml
15:10:37 net. SF. hibernate. cfg. Configuration getconfigurationinputstream
Information: configuration resource:/hibernate. cfg. xml
15:10:38 net. SF. hibernate. cfg. Configuration addresource
Information: Mapping Resource: COM/huangdong/demo/Dao/sysuser. HBM. xml
15:10:38 net. SF. hibernate. cfg. Binder bindrootclass
Information: mapping class: COM. huangdong. Demo. Dao. sysuser-> sysuser
15:10:39 net. SF. hibernate. cfg. Configuration doconfigure
Information: configured sessionfactory: NULL
15:10:39 net. SF. hibernate. cfg. Configuration secondpasscompile
Information: processing one-to-register Association Mappings
15:10:39 net. SF. hibernate. cfg. Configuration secondpasscompile
Information: processing one-to-one association property references
15:10:39 net. SF. hibernate. cfg. Configuration secondpasscompile
Information: processing foreign key constraints
15:10:39 net. SF. hibernate. dialect. dialect <init>
Information: Using Dialect: net. SF. hibernate. dialect. oracle9dialect
15:10:39 net. SF. hibernate. cfg. settingsfactory buildset.pdf
Information: JDBC result set fetch size: 50
15:10:39 net. SF. hibernate. cfg. settingsfactory buildset.pdf
Information: Use Outer Join fetching: True
15:10:39 net. SF. hibernate. Connection. drivermanagerconnectionprovider configure
Information: Using hibernate built-in Connection Pool (not for production use !)
15:10:39 net. SF. hibernate. Connection. drivermanagerconnectionprovider configure
Information: hibernate connection pool size: 20
15:10:39 net. SF. hibernate. Connection. drivermanagerconnectionprovider configure
Information: Using DRIVER: Oracle. JDBC. Driver. oracledriver at URL: JDBC: oracle: thin: @ localhost: 1521: hdorc
15:10:39 net. SF. hibernate. Connection. drivermanagerconnectionprovider configure
Information: Connection Properties: {user = HD, password = ABC, pool. size = 1}
15:10:39 net. SF. hibernate. transaction. transactionmanagerlookupfactory gettransactionmanagerlookup
Information: No transactionmanagerlookup configured (in JTA environment, use of process level read-write cache is not recommended)
15:10:45 net. SF. hibernate. cfg. settingsfactory buildset.pdf
Information: Use scrollable result sets: True
15:10:45 net. SF. hibernate. cfg. settingsfactory buildset.pdf
Information: JDBC 2 max batch size: 30
15:10:45 net. SF. hibernate. cfg. settingsfactory buildset.pdf
Information: echoing all SQL to stdout
15:10:45 net. SF. hibernate. cfg. settingsfactory buildset.pdf
Information: Query Language substitutions :{}
15:10:45 net. SF. hibernate. cfg. settingsfactory buildset.pdf
Information: cache provider: net. SF. ehcache. hibernate. Provider
15:10:45 net. SF. hibernate. cfg. Configuration configurecaches
Information: instantiating and caching ing caches
15:10:46 net. SF. hibernate. impl. sessionfactoryimpl <init>
Information: building session Factory
15:10:47 net. SF. hibernate. impl. sessionfactoryobjectfactory addinstance
Information: No JNDI name configured
Hibernate: insert into sysuser (username, userpasword, lastlogin, userid) values (?, ?, ?, ?)
Finally, we can see the database operation statements generated by hibernate. Here you can say that you have successfully run many things. Let's list them again. Consider how they are run and deployed. What are they:

Eclipse
Myeclipse
Tomcat
Oracle/oracle JDBC driver
Hibernate
Struts (we haven't used its function yet)
Check whether the data in the table is updated.
In the database access view, you can easily view the data in the data table:

In this way, we can see the data in the sysuser table in the Database Data View:

Stay at the end
This article briefly introduces the basic environment for developing Java-based Web applications, and introduces a series of development tools and components. These tools have more functions, so we will not introduce them here. Please refer to the instructions of eclipse and myeclipse. They also have many rich functions. For the struts and hibernate powerful componentsArticle.

If you have any comments or suggestions for this article, please contact me and let me know your thoughts. You can also discuss various Java-related technologies in the Java version of technology sky BBS.

You can download the complete Eclipse project package from here.

In addition, all the code in this article is tested by the author in the following environments:

Eclipse 2.1.2
Struts 1.1
Hibernate 2.1.1
Tomcat 4.1.29/jetty 4.2.15
Com. tanghan. plugin_0.1.0.12.21
JDK 1.4.2 _ 02 for Windows/FreeBSD 4.8/FreeBSD 4.9
FreeBSD 4.8/FreeBSD 4.9/Windows 2000/Windows XP
Oracle 9.2.0.1.0

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.