Foreword
Hibernate is a very good and has been used in large quantities of database persistence tools that have become more mature. This article is mainly for developers using Hibernate. This chapter is mainly to illustrate the initial settings of the development environment used in the Hibernate Development Guide and use a simple example to illustrate Hibernate.
The tools mainly used herein are:
JDK: JDK 1.4.2 Development Environment: Eclipse 2.1.2 Hibernate 2.1 Database: Oracle 9i Hibernate's Eclipse plugin: Tanghan Plugin Please take a look at whether you have installed these software on your machine, for the database, just because of my machine Oracle has been installed, using other databases will not have much difference. My example also uses a Struts framework, because I think Struts in the web application framework is a very good choice, and the Hibernate is accessed, and the two matches better results. In order to use Struts, please confirm that you have the following software installed:
Web Application Server: Tomcat 4.x Struts 1.1 Pack Eclipse J2EE Integrated Plug-in: MyECLIPSE 2.7RC1 or above (2.7 Starting Struts Support) If you don't want to use myEClipse, you can use Lomboz and Easystruts to replace its Features. The specific software installation and plug-in installation is not here. Let's talk about the configuration after installing.
Software configuration
Let's first configure the database, and write down the relevant information required for database development.
Oracle related configuration parameters
I created a separate user in Oracle: HD, set its password to: ABC. Assign the corresponding database space for the user, the detailed configuration method and information are no longer said, in short, you need to get the following information for development:
Machine Address: HDIBM (Because of the local machine can also use localhost and 127.0.0.1, if another machine uses the IP address of the machine) Oracle's listening port: 1521 Database instance name: HDORC Access User Name: HD Access Password: ABC needs to be aware that the role of the HD user is assigned at least Connect. In addition, it is assigned enough or unlimited limits in the table space he use, otherwise it will encounter problems during development. In addition to these, you need to download the latest JDBC package from the installed Oracle or Oracle website. It has two packages, one of which is driven with JDK, the other is multilingual support package (here we don't use OCI Drive, drive using Thin). Because I used JDK for 1.4, I used the driver package.
The multilingual support package used by OJDBC14.JAR and JDK1.4 is the same as JDK1.2.
NLS_CHARSET12.JAR.
In the database, we build some tables for program development, take a simple user management as an example, we first create a simple user table (Sysuser):
Table Name: Sysuser User ID: UserId (Vchar: 32) User Name: UserName (Vchar: 20) User Password: UserPasword (Vchar: 20) User Last Listing: 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
Tomcat installation is very simple, download the related installation package from the Tomcat website, you can solve the relevant directory. After installing Tomcat, you need to write down the following information:
Tomcat installation directory Tomcat's listening port (default is 8080)
Configuring Hibernate for Eclipse plugin TANGHAN PLUGIN
There will be many people without starting with this plugin, mainly, I don't know where to use this plugin. The first two views provided by this plugin: Database Access View and Database Data View. Select these two views through windows> Display View> Others on the menu:
Open the Database Access View view, let's configure Oracle drivers, with mouse right-click Oracle Thin Driver> Modify Driver Information:
Here:
Drive Name: Oracle Thin Driver Driver Package: Browse Choose Your Ojdbc14.jar File Driver Class: Oracle.jdbc.driver.OracleDriver Driver Prefix: JDBC: Oracle: Thin:
Here:
Database connection name: HDTestDB Drive Name: Oracle Thin Driver (is the above we are built) driver class: Oracle.jdbc.driver.OracleDriver database connection: JDBC: Oracle: Thin: HD @ Abc // HDIBM: 1521 / HDORC users Name: HD Password: ABC Next We tried to connect to the database:
Need to choose SHEMAS, select HD from the drop-down list, press the OK button. If you can see the choice of the SHEMAS dialog, you have no problem with your database configuration. We can see the tables and table structures in the library in Database Access View:
Configure myECLIPSE
Download from MyEclipse's website to the latest MyEclipse trial and Struts-related TLD and LIB packages. After installing myECLIPSE, configure Tomcat. It is mainly to configure the related path of Tomcat:
It should be noted that Tomcat must use a JDK instead of JRE, you can choose a JDK in Tomcat's configuration tree for Tomcat startup:
Next, the Struts packet solution downloaded from the website is disconnected into the file system (you can also remove the lib and TLD in the Struts 1.1 package), configure the Struts 1.1 related package in MyECLIPSE: These configurations are available Establish a simple project.
Establish initial Struts project
We first build a project, prepare for subsequent in-depth development, this project is a simple framework, import Tomcat deployment support, establish a library path with struts and hibernate.
Establish web application project
First use the wizard to create a web module provject:
Enter information about Web Project:
Enter one by one shown in the figure. Click to complete the establishment Project.
Join the Tomcat deployment support for the project
Next, join the Tomcat deployment support for the project:
In the pop-up dialog, point add and select Tomcat 4 in the drop-down box:
Join Struts Support for web applications
Join the project to join the Struts Support:
In the pop-up dialog box, press the image to enter information:
This joins the Struts support for the web application project, which automatically adds the TLD file (tag lib document) for the project to join the Struts support package and Struts. After that, we can see:
Join Hibernate support for web applications
There is a lot of JAR in Hibernate. It is not recommended to join all. The following is the JAR package you have to join (these package hibernate2.jar is in the lib subdirectory in the root:
Hibernate2.jar: Hibernate's core library. CGLIB2.jar: Hibernate is used to implement the library required for the dynamic generation of the PO bytecode. Commons-Collections.jar: Apache Commons provides a stronger collection class than java.util. *. Commons-lang.jar: Apache Commons provides the ability to extend java.lang. *. Commons-logging.jar: A universal log interface tool provided by Apache Commons. It uses log4j, JDK's java.util.logging, the order of Commons-logging SIMPLE Logger to find available Log APIs. Dom4j.jar: An access to XML interface implementation, Hibernate uses this package to complete the XML operation. Odmg.jar: ODMG is an ORM specification, Hibernate uses this package to implement ODMG specification. Xalan.jar, Xerces.jar and XML-Apis.jar: XSLT processors, SAX resolution, standard JAXP API packages are processed for XML. (Most application servers bring these three packages) The following packages can be added as options based on the situation in your application, by yourself:
C3p0.jar: The package used by the C3PO database connection pool. Commons-dbcp.jar and Commons-pool.jar: Apache Commons The package used by DBCP connection pool is available. JBoss-cache.jar, Concurrent.jar, JBoss-Common.jar, JBoss-JMX.jar, JBoss-System.jar: Treecache, which implements a clustered cache. Connector.jar: Standard JCA API package. Most application servers have belong. (*) EHCACHE.JAR: EHCACHE CACHE Pack, Hibernate uses this package to complete the Cache function. Jaas.jar: Standard JaaS API package. Most application servers also have this package, this package is used for JCA. (JDK 1.4 also already contains this package) JCS.jar: JCS Cache package. JDBC2_0-stdext.jar: Standard JDBC 2.0 API extension. Most application servers also contain this package. Swarmcache.jar and jgroups.jar: Swarmcache can be copied to the package used by the distributed cache. It uses JavaGroups to group communication, which is suitable for database applications for cluster environments. (*) JTA.jar: Standard JTA API package. Most application servers also have this package. Log4j.jar: log4 pack, log4j is a very good choice in the Logger tool. Oscache.jar: The OSCache package provided by OpenSymphony for the database of cache. Proxool.jar: Proxool JDBC Database Connection Pack. There are also some other packages, not the bag used in the run, attached here to learn: Ant.jar: Compiling the ANT core package used when Hibernat. JUnit.jar: JUnit Test Frame Pack, compile time to test the test code. Optional.jar: Ant use of the auxiliary package, including some additional TASK. The method of adding the package is simple, using the Explorer to drag the JAR file into the lib directory in the web-inflight of the Web directory. MyEclipse automatically adds all the JAR files in the directory to the Compilation ClassPath in the Project. Note that except for the packets, please join the project in front of the package. Since it is used to use Tomcat, the XML package in the mustable package can not be added. As shown below:
Join the JDBC driver for web applications
The previously prepared Oracle driver package is also added to the web project. Mainly these two files:
NLS_Charset12.jar ojdbc14.jar
The picture below is a list of configured the last package, please check one by one:
Configure Hibernate configuration files
Configure Hibernate database connection configuration
The connection configuration of the database is very simple, establish an XML file in the SRC directory of the project, named hibernate.cfg.xml. The content of this file is:
xml version = '1.0' encoding = 'UTF-8'?>
Diagect: Used Oracle9 Configuring Connection.driver_Class: Oracle's JDBC Drive Class Name Connection.userName: Oracle Database Access User Name Connection.Password: Oracle Database Access Password Connection.URL: Oracle Database Access URL Connection.Pool.Size: Database connection Pool size statement_cache.size: JDBC Statement buffer size JDBC.FETCH_SIZE: Set the number of records that JDBC's statement read data JDBC.BATCH_SIZE: Set the batch delete, bulk update and batch quantity of the database Batch size show_sql when inserted: Set whether to display the SQL statement submitted to the database on the console, which is a list of mapped files that we have a map of the database table when developing commissioning. We will map the sysuser table below, so now it has been added. And this XML will be placed in the com.huangdong.demo.dao package, so you have to write the path when LOAD. Configure the Hibernate table map
Select the sysuser table in the Database Access View, select Generate HBM files in the menu:
Enter the relevant information in the wizard dialog box:
After completing the button, you will generate the sysuser class and the sysuser.hb.xml file in the com.huangdong.demo.dao package.
Since there are many inconvenient places in Java using java.util.date, I changed the Java attribute after LastLogin's map to Calendar.
This is a modified sysuser.hbm.xml file:
XML Version = "1.0" encoding = "UTF-8"?>
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 () {Retur n 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 return false ((other instanceof SysUser)!); SysUser castOther = (SysUser) other; return new EqualsBuilder () .append (this.getUserid (), castOther.getUserid ()). ISEquals ();} public int.come (). .append (getUserid ()) .tohashcode ()) .Tohashcode ();}}
Create a servlet framework
Use the wizard of the New Servlet to create a test-used servlet, the following image is the parameters and options you entered when you create a servlet:
In the next XML Wizard dialog box, you can remember that DISPLAY NAME and DESTEM FUNCTION Servlet are cleared, as shown below:
This creates an initial servlet framework.
Write a database connection acquisition class
We write a separate class that allows database connection session from SessionFactory. This class name is Hibernateutil, we put it in 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 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);} returniti} public static void closesession () throws hibernateException {session s = (session) session.get (); session .set (NULL); if (s! = null) s.close ();}}
We can get database connections through the currentSession method. If there is available session in the system, it will be reversed back, and a new session will be created if it is not. When the SESSION operation is complete, the operator is required to use the CloseSession method to release the session used. Establish test bean
Next we create a TestHibernate Java bean, which mainly adds some Hibernate test methods. The following is the information created by this class:
We join a way to add data to the database:
public boolean TestAdd () {try {Session session = HibernateUtil.currentSession (); Transaction tx = session.beginTransaction (); SysUser user = new SysUser (); user.setUsername ( "Ya-Ya"); user.setUserpasword ( "uhkuhkqepdwqi "); user.SetLastLogin (Calendar.GetInstance ()); session.save (user); tx.commit (); hibernateutil.closesis ();} catch (HibernateException E) {E.PrintStackTrace (); return false;} Return True;}
The first time I wrote this code very unexpectedly, I always feel more, but I really do this, we only use such a few words to add a record to the database.
Tune TestAdd method in servlet
This is very simple, change the Doget method for 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 ( " ") Out.println (" body>"); out.println (" html>"); out.flush (); out.close ();} If the TestAdd method performs success, it will return TRUE on the page, otherwise false will be returned. Let's test one below. Test our first servlet-based Hibernate app boot Tomcat If you are configured by this article, you will not have any problems here. If you operate, you will enter the debug view of Eclipse: See all threads in the Debug view and see "Starting Coyote HTTP / 1.1 On Port 8080" in the console window indicates that Tomcat starts successful and listened to 8080 ports, as shown below: Open the browser and enter: in the address bar: Http: // localhost: 8080 / demo / servlet / testservlet If the returned page is shown below, the database update is successful: At the same time we can see Hibernate's log output in the console of Eclipse, explain the details of its work: 2003-12-26 15:10:37 net.sf.hibernate.cfg.Environment Information: using dialact: net.sf.hibernate.diaalect.racle9diaalect 2003-12-26 15:10:39 net.sf.hibernate.cfg.SettingsFactory BuildSettings Information: JDBC Result Set Fetch Size: 50 2003-12-26 15: 10:39 net.sf.hibernate.cfg.SettingsFactory buildSettings information: Use outer join fetching: true 2003-12-26 15:10:39 net.sf.hibernate.connection.DriverManagerConnectionProvider configure information: Using Hibernate built-in connection pool (NOT for production us!) 2003-12-26 15:10:39 net.sf.hibernate.Connection.driverManagerConnectionProvider Configure Information: Hibernate Connection Pool Size: 20 2003-12-26 15:10:39 Net.sf.hibernate .connection.DriverManagerConnectionProvider configure information: using driver: oracle.jdbc.driver.OracleDriver at URL: jdbc: oracle: thin: @localhost: 1521: hdorc 2003-12-26 15:10:39 net.sf.hibernate.connection. DriverManagerConnectionProvider Configure Information: Connection Properties: {user = HD, Password = ABC, POOL.SIZE = 1} 2003-12-26 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) 2003-12-26 15 : 10: 45 Net.sf.hibaRnate.cfg.SettingsFactory BuildSettings Information: Use Scrollable Result Sets: True 2003-12-26 15:10:45 Net.sf.Hibernate.cfg.SettingsFactory BuildSettings Information: JDBC 2 Max Batch Size: 30 2003-12-26 15:10:45 Net.sf.hibFactory.cfg.SettingsFactory BuildSettings Information: echoing all sql to stdout 2003-12-26 15:10:45 net.sf.hibernate.cfg.SettingsFactory BuildSettings information: Query Language Substitutions: {} 2003-12-26 15:10:45 Net.sf.hibernate.cfg.SettingsFactory BuildSettings Information: cache provider: Net.sf.ehcache.hibernate.Provider 2003-12-26 15:10:45 Net.sf.hibernate.cfg.Configuration ConfigureChes Information: Instantiating and configuring caches 2003-12-26 15:10:46 net.sf.hibernate.impl.SessionFactoryImpl Eclipse MyEclipse Tomcat Oracle / Oracle JDBC Driver Hibernate Struts (in fact, we have not used its feature yet) View whether the data in the table is updated View the data in the data table in the Database Access View in the Database Access View: This will see the data in the sysuser table in Database Data View: Stay in the final This article simply introduces you to the development of Java-based web applications, and introduces a series of development tools and components. These tools have more features, this is no longer introduced, please refer to Eclipse, MyEclipse documentation, and there are many rich features. Two powerful components of Struts and Hibernate are later slowly illustrated in subsequent articles. If you have any comments and suggestions for this article, please contact me, tell me your thoughts, and can also discuss various technologies related to Java in the Java version of the technology sky BBS. You can download it from here to a complete Eclipse Project package. In addition, all code herein is not issued by the author's actual test 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