A complete example of using Hibernate

xiaoxiao2021-03-06  52

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

factory

org.apache.commons.dbcp.basicDataSourceFactory

driverclassname

Org.gjt.mm.mysql.driver

URL

jdbc: mysql: /// Test

Username

root

Password

maxactive

20

maxidle

10

maxwait

-1

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">

Java: Comp / Env / JDBC / Hibernate

false FALSE

Net.sf.hibernate.dialect.mysqldiaAlaforct

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

"- // 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"

>

Name = "name"

TYPE = "string"

Update = "true"

INSERT = "True"

COLUMN = "Name"

/>

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:

...

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"%>

<%

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:



:: Press the name of the name ::

Name:



:: Delete a course ::

ID:



:: View all course ::

First pass a value object course (this class is exactly the lasting object used by Hibernate, here is used as value objects to pass data) received the obtained parameters, and then the coursebean's AddCourse (Course) method saves the data to the database. It can be seen that by using Hibernate, it is very simple to add data from the form to the database. Query the JSP code of the blurry lookup, such as routine 8

Routines 8 Press the name of the name to find Course

<% @ page import = "java.sql. *, java.util. *, com.hellking.study.hibernate.course" errorpage = "error.jsp"%>

...

<% TRY

{

Iterator it = coursebusiness.getsomecourse ((String) Request.GetParameter ("name"));

While (it.hasnext ())

{

Course Temp = (Course) it.next ();

Out.println (" " TEMP.GETID () "");

Out.println ("" TEMP.GETNAME () " ");

}

}

Catch (Exception E)

{

Out.println (E.GetMessage ());

}

%>

.

It actually calls a CourseBean's Iterator GetSomeCourse (String Name) method. Let's review the code in this method:

/ **

* Press COURSE's name for blurring

* /

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;

}

Before the query, first call the Begintractions method to start the new Hibernate transaction, then create a Query object, when you create this object, specify the statement of the query.

Note, in the query statement:

Select C from Course As C Where C.Name Like: Name

Although it is similar to the ordinary SQL statement, it is different, in the database, the name of the table used is coursees, and in this query statement is Course, it is consistent with the name of the lasting object, that is, this The concept of queries is to query persistent objects, not a database record. After you create query object Query, you need to set the query parameters, which will similar ways to the parameters in the PreparedStatement object in the JDBC. Returns an Iterator object by "Iterator IT = Query.Iterate () statement. Here, the Query mechanism provided here, the general JDBC query returns the ResultSet object, and the return here is the Iterator containing the CourseBean object.

To query all Course in the system, it is also very simple, and can be implemented by the code shown in routine 9.

Routines 9 Query all court in the database

...

...

<% TRY

{

Iterator it = coursebusiness.getallcourses ();

While (it.hasnext ())

{

Course Temp = (Course) it.next ();

Out.println (" " TEMP.GETID () "");

Out.println ("" TEMP.GETNAME () " ");

}

}

Catch (Exception E)

{

Out.println (E.GetMessage ());

}

%>

...

In fact, calling the CourseBean's getAllCourses method, which is no longer introduced like the GetSomeCourse method mechanism.

Deleting Data In JSP, using the following code to perform the delete operation.

Routines 10 Delete Records of Courses Table in Database

...

Delete ID is: <% = Request.getParameter ("ID")%> COURSE :::

<% TRY

{

CourseBusiness.Deletecourse (Request.GetParameter ("ID"));

Out.println ("Delete Success");

}

Catch (Exception E)

{

Out.println ("There is no such record");

}

%>

Let's see the specific code to execute the delete operation in the CourseBean:

/ **

* 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);

}

In this method, first start a transaction, then load the persistent object of the specified ID through the session.Load (Course.class, ID) method, followed by "session.delete (course)" to delete the loaded Course, and End Hibernate transaction. Summary The following summarizes the development process of using Hibernate:

1, configure hibernate (once);

2, determine the data table;

3. Create a lasting object;

4. Writing the mapping description of objects and data sheets;

5, write and business logic.

In fact, there is no difference between the above process and using EJB: When using EJB, first of course, the environment is also a configuration environment, initialize the data table; then create an entity bean (Object to Hibernate's persistent object); next to write deployment descriptor (EJB- JAR.XML, manufacturer's proprietary deployment description, in these deployment descriptors, specify the mapping relationship of the EJB and data tables, if multiple entity beans are associated, need to describe the relationships between them, these descriptions correspond to Hibernate's persistent object description, such as course.hbm.xml; often do not operate the entity bean directly in the application, but through business objects (such as session beans), the session beans here can be implemented in Hibernate. JavaBean of business logic. It is just a simple class ratio, not absolute, such as we can also access Hibernate persistent objects in the session bean, which means using hibernate, which can also put business logic in session beans.

Through this study, I believe that readers have a preliminary understanding of Hibernate and can use Hibernate to develop a simple application. In the next article, we will learn how to use hibernate to map for complex data tables and maintain the relationship between them.

Reference

Http://www.apache.org Download Tomcat. Hibernate's official website, http://hibernate.bluemars.Net/, contains the latest information on Hibernate. Hibernate Chinese Forum, hibernate.fankai.com contains more than Hibernate. The Hibernate discussion site, www.jdon.com, the warm discussion of Hibernate, JDO, CMP, etc. 1: http://www.jdon.com/jive/thread.jsp? Forum = 16 & three = 6062 & start = 0 & msrange = 15 On the warm discussion of Hibernate, JDO, CMP, 2: http://www.theserverside.com/discussion/thread.jsp? Thread_id = 19732Hibernate2 Reference Documentation, you can get, very good reference information from Hibernate official website. Hibernate In Action, a very professional Hibernate reference book, the main developer of the Hibernate project, GAVIN KING, MANNING Publishing House. You can get some chapters of this book from http://www.theserverside.com. With regard to Chen Yaqiang: Beijing Huayuan Tianyi Technology Co., Ltd. Senior software engineer, good at J2EE technology, participated in the design and development of multiple J2EE projects, has great interest in web services and has certain project experience. Love to learn, like new technologies, have participated in the writing of many books. Helloger friends, you can contact him via cyqcims@mail.tsinghua.edu.cn.


New Post(0)