Beijing Huayuan Tianyi Technology Co., Ltd. Senior Software Engineer
October 2003
Object, mapping (ORM) is a time-consuming job. In the Java environment, there are several frameworks to represent persistent data, such as entity beans, OJB, JDO, Hibernate, etc. Hibernate is a new ORM mapping tool not only provides mapping from Java class to data sheets, but also provides data query and recovery. This article describes how to configure Hibernate in Web application development and use Hibernate to develop a specific instance. You need the following knowledge and tools before reading this article:
Tomcat 5.09, you can download from www.apache.org; Hibernate 2.0 related operational environments, you can download from http://hibernate.boemars.net/; at least one database server and has a related JDBC driver.
The reference materials of this article are found.
Introduction to object-oriented development methods is the mainstream of today, but we have to use relational databases, so in environments developed in an enterprise application, objects, and ORMs are a time consuming job. The maps of mapping and persistent data around the subject relationship have developed some APIs and frameworks in the Java field, which is briefly introduced separately.
JDBC can be said to be the most original and direct way to visit the lasting data layer. In enterprise-level application development, we may use the DAO (Data Access Object) mode to connect the data to the package and then call in other layers. The advantage of this approach is that the operation is the highest, and the disadvantage is to closely couple the DAO object and SQL language together make it difficult to maintain in the big project. But no matter what to say, using JDBC to directly access the lasting data layer is the most widely used in today's enterprise applications.
The entity bean is a way to represent and access persistent data in the J2EE platform. Although entity bean is a convenient and quick approach, we need to purchase an additional EJB container at runtime (of course, there are free EJB containers, such as jboss), and use different application servers, need to write different deployment descriptions, Make transplant enterprise applications under different application servers will bring some difficulties.
In addition, in the Java field, there are some frameworks that represent persistent data, such as JDO and OJB, which are not described in detail here.
Hibernate is a new ORM mapping tool not only provides a map from the Java class to the data sheet, but also provides a data query and recovery mechanism. To manually operate the database relative to using JDBC and SQL, use Hibernate, which can greatly reduce the workload of the operational database.
Hibernate can be integrated with a variety of web servers or application servers, and now support almost all popular database servers (up to 16).
Let's introduce how to combine Hibernate 2.0 and Apache Tomcat5.0 in web applications using hibernate.
Configure
1. Download and install Tomcat and download the Hibernate's operating environment (mainly including some JAR packages).
2. Copy the JDBC driver of the database you want to use to the% Tomcat_Home% / Common / Lib directory. The author uses mysql, the corresponding driver's JAR package is mm.mysql-2.0.4-bin.jar.
3, create a new web application in Tomcat's WebApps directory, named hibernate.
4. Apply Hibernate2.jar provided by Hibernate and some third-party running libraries to the hibernate / web / inf / lib directory. (These third-party runs are included in the downloaded hibernate lib directory) 5, in% Tomcat_Home% / conf / server.xml web application and data sources. Add the following configuration description in Server.xml.
Routine 1 Configure web application
parameter>
parameter>
parameter>
parameter>
parameter>
parameter>
parameter>
parameter>
Resourceparams>
Context>
Here, a web application called Hibernate is configured, and a data source is configured. The JNDI name of the data source is JDBC / Hibernate. You need to modify the link properties of the data source based on the situation.
6. The next step is to write Hibernate configuration descriptor. You can use an XML configuration description, or an attribute-based configuration description can also be used. Use XML-based configuration description herein here. Enjoy a hibernate.cfg.xml file in the hibernate / web-inf / class directory. Then add the content shown in routine 2.
PUBLIC "- // Hibernate / Hibernate Configuration DTD // EN"
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
session-factory>
Hibernate-Configuration>
Note that the connection.dataSource property must be the same as the properties of the data source configured in Server.xml. If you don't use MySQL, you need to change the DIALECT property. To now, the configuration is basically completed, let's develop a simplest application.
Develop a persistent object, write a map Description We use Hibernate to encapsulate a simple data sheet. The name of this table is Courses, which has two fields, one is ID, it is the primary key of the CourseS table; the other is Name, indicating the name of Courses. Use the following scripts in the database to create this table:
Create Table Courses (Courseid Varchar (32) Not Null, Name Varchar (32), Constraint PK_Courses Primary Key (Course));
The next task is to write a persistent object for the CourseS table, as shown in routine 3.
Roller 3 Courses' persistence object (coursees.java)
Package com.hellking.study.hibernate;
Import java.util.set;
/ **
* Represents classes of the COURSE table in Hibernate.
* /
Public Class Course
{
/ ** Each property and a field of the table correspond to ** /
Private string id;
PRIVATE STRING NAME;
/ ** Students indicate students in Course, will only be used later, no matter whether it is ** /
PRIVATE SET STUDENTS;
/ ** Access method for properties ** /
Public void setid (String String) {
ID = String;
}
Public string getId () {
Return ID;
}
Public void setname (String name)
{
THIS.NAME = Name;
}
Public string getName ()
{
Return this.name;
}
Public void setStudents (SET Stud) {
THIS.STUDENTS = STUD;
}
Public set getstudents ()
{
Return this.students;
}
}
It can be seen that two attributes, IDs, and names, and the fields of the table Courses are one or one in the Course class, and the type is consistent. Writing a long-lasting object, the next task is to write objects, a relationship map description. In the Hibernate / WEB-INF / CLASSES directory, create a new course.hbm.xml description file, as shown in routine 4.
Routine 4 course.hbm.xml
XML Version = "1.0"?>
"- // Hibernate / Hibernate mapping DTD 2.0 // en"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
Name = "com.hellking.study.hibernate.course" Table = "coursees" Dynamic-update = "false" > Name = "id" COLUMN = "courseid" TYPE = "string" Unsaved-value = "any" > id> Name = "name" TYPE = "string" Update = "true" INSERT = "True" COLUMN = "Name" /> clas> hibernate-maping> In the course.hbm.xml mapping file, specify the table and mapping of the class to map, and specify the map relationships of the respective fields of the table and the various fields in the Java object, such as the ID attribute in the Course object corresponding to the Courses table. CourseID field. The next task is to specify this mapping relationship in hibernate.cfg.xml. As follows: ... session-factory> Write business logic to this, we have already packaged a table named coursees and configured. The next task is to use them in web application development. To demonstrate different types of operations in the database in Hibernate, our development Web application has the following features: Add a course; delete a course; make a blur search according to Course; check all the course in the system. Although we can use Hibernate directly in JSP, it is often not like this, but puts these business logic in JavaBean, and then calls JavaBean in JSP to access the Hibernate package. Since accession has some common operation by using Hibernate, we will package these commonly operated operations in a specialized class, such that other classes can inherit it, as shown in routine 5. Routines 5 HibernateBase.java Package com.hellking.study.hibernate; Import net.sf.hibernate. *; Import net.sf.hibs. *; Import java.util. *; Import java.io.ioException; Import java.io.printwriter; Public Abstract Class HibernateBase { Protected sessionFactory sessionFactory; // session factory for creating a session protected session session; // hibernate session Protected Transaction Transaction; // Hibrante transaction Public HibernateBase () THROWS HIBERNATEXCEPTION { this.inithibernate (); } // Help method protected voidiniBernate () Throws HibernateException { // Load configuration, construct the sessionFactory object SESSIONFACTORY = New Configuration (). CONFIGURE (). BuildSessionFactory (); } / ** * Start a hibernate transaction * / protected void begintransaction () Throws HibernateException { SESSION = sessionFactory.openSession (); Transaction = session.begintransaction (); } / ** * End a Hibernate transaction. * / Protected void endtransaction (boolean commit) Throws HibernateException { IF (commit) { Transaction.commit (); } else { // If it is read-only, there is no need to commit this transaction. Transaction.rollback (); } session.close (); } } The business logic class is written below, and a new JavaBean called CourseBean, and coursebean inherits the HibernateBase class, the code is as shown in routine 6. Routine 6 coursebean.java Package com.hellking.study.hibernate; Import net.sf.hibernate. *; Import net.sf.hibs. *; Import java.util. *; / ** * And course related business logic * / Public Class CourseBean Extends HibernateBase { Public coursebean () THROWS HIBERNATEXCEPTION { Super (); } / ** * Add a Course * / Public Void AddCourse (Course St) throws HibernateException { Begintransaction (); Session.save (st); EndTransaction (TRUE); } / ** * Query all Course in the system, returning is an item containing the COURSE persistent object. * / Public iterator getAllcourses () THROWS HIBERNATEXCEPTION { String querystring = "Select Course from Course As Courses"; Begintransaction (); Query Query = session.createQuery (queryString); Iterator it = query.Itemate (); Return IT; } / ** * Remove the court of a given ID * / Public void deletecourse (String ID) throws HibernateException { Begintransaction (); Course Course = (Course) session.load (course.class, id); Session.delete (course); EndTransaction (TRUE); } / ** * Press COURSE's name to make a fuzzy lookup, returned to Iterator containing a COURSE persistent object. * / Public iterator getsomecourse (String name) throws HibernateException { String queryString = "SELECT C from course as c where c.name like: name"; Begintransaction (); Query Query = session.createQuery (queryString); Query.setString ("name", "%" Name "%"); Iterator it = query.Itemate (); Return IT; } } 4 business methods have been encapsulated in CourseBean, which you can add other business methods depending on the situation. In CourseBean, operate potential database resources via Hibernate. To save Course data to the database, you can pass: Session.save (course); The method is saved, which is equivalent to performing the following statement in JDBC: Connection con = ... Statement Stmt = con.createstatement (); Stmt.executeUpdate ("INSERT INTO COURS VALUES ('" Course.getID (), "', '" course.getname () ""); C. close (); It can be seen that by using Hibernate, the complexity of data access can be greatly reduced. Call business logic in JSP adding data CourseBean This business object encapsulates the interaction of Hibernate, thus making JSP and Hibernate relationships. Let's see some code of the test home page, as shown in routine 7. Routine 7 Tests Hibernate Development Application (Course.jsp) <% @ Page Import = "java.sql. *, java.util. *" ErrorPage = "error.jsp"%> jsp: usebean> <% Try { IF (Course.GetId (). Equals (null) || courtid (). Equals ("")); Else Coursebusiness.addCourse (Course); %> Successfully added course: Name: <% = course.getname ()%> ID: <% = course.getid ()%> <% } Catch (Exception E) { } %>
: Add a course ::
ID:
Name:
form>
:: Press the name of the name ::