Use hibernate to achieve persistent objects

xiaoxiao2021-03-06  100

Use hibernate to implement a lasting object content: introduction Configure development persistent objects, write mapping descriptions Writing business logic Calling business logic summary in JSP About the author Java area: teaching tools and product code and components All articles practical skills Chen Yaqiang ( Cyqcims@mail.tsinghua.edu.cn) 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 source. 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 is here, configured a web application called Hibernate, and configures A data source, 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.

java: comp / env / jdbc / hibernate false net.sf.hibernate.diaalect.MysqldiaLect

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 {/ ** One field of each property and table corresponds to the ** / prinity; / ** StudentS represents students in Course, will be used later, temporarily regardless of ** / Private set students; / ** Access method of property ** / public void setId (String string) {id = string;} public string getId () {return ID;} public void setname (String name) {this.name = PUBLIC STRING GETNAME () {Return this.name;} public void setstudents (SET STUD) {this.students = stud;} public set getstudents () {return this.students;}} can be seen, in the Course class There are also two attributes, IDs, and names, and the fields of its properties and table coursees are one or one, 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

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.hib.hibernate. *; import net.sf.hibernate.cfg. *; import java.util. *; import java.ioException; import java.io.printwriter;

public abstract class HibernateBase {protected SessionFactory sessionFactory; // session factory, used to create sessions protected Session session; // hibernate session protected Transaction transaction; // hiberante transaction public HibernateBase () throws HibernateException {this.initHibernate ();} // Help method protected void inithibernate () THROWS HibernateException {

// Load configuration, construct sessionFactory object sessionFactory = new configuration (). Configure (). BuildSessionFactory ();} / ** * Start a hibernate transaction * / protected () 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 a read-only operation, 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.hibernate.cfg. *; import java.util. *;

/ * ** course related and business logic * / public class CourseBean extends HibernateBase {public CourseBean () throws HibernateException {super ();} / ** * increase a Course * / public void addCourse (Course st) throws HibernateException {beginTransaction (); Session.save (st); endtransaction;} / ** * Query all Course in the system, returning is the Iterator containing the COURSE persistent object. * / Public Iterator getAllCourses () throws HibernateException {String queryString = "select courses from Course as courses"; beginTransaction (); Query query = session.createQuery (queryString); Iterator it = query.iterate (); return it;} / ** * delete the given ID course * / public void deleteCourse (String id) throws HibernateException {beginTransaction (); Course course = (Course) session.load (Course.class, id); session.delete (course); endTransaction (TRUE);} / ** * Press COURSE to make a fuzzy lookup, returning is an item 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 "% "); item it = query.Iterate (); return it;}} 4 business methods in CourseBean, 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 (" Insert Into Course Values ​​("Insert Into Course Values" "','" Course.getName () ")") Conit (); 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) || course.getid (). Equals (")); else Coursebusiness. AddCourse (Course);%> Successfully added course:
Name: <% = course.getname ()%> ID: <% = course.getid ()%> <%} catch (Exception E) {}% >



: Add a course ::
id: < Br> name:


:: Press Name Fuzzy lookup:
name:


:: Delete a course ::
ID:


:: See 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, as shown in 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 {iter = 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 Coursebean Iterator getSomeCourse (String Name) method. Let's review the code in this method:

/ ** * by name of course fuzzy search * / 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 "%"); item it = query.Iterate (); 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 {ipalcourses (); while (it.hasnext )) {Course temp = (course) it.next (); out.println (" " TEMP.GETID () ""); out.println (" " Temp.getname () " ");}} catch (exception e) {outputln (E.getMessage ());}%> ...

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

delete data

In JSP, use the following code to perform the delete operation.

Routines 10 Delete Records of Courses Table in Database

... Delete ID is: <% = Request.GetParameter ("ID")%> Courses: :::

<% try {coursebusiness.deletecourse ("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:

/ ** * CourseCourse (String ID) that deletes a given ID (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.


New Post(0)