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
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.
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 {/ ** 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
xml version = "1.0"?>
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"%>
Name: <% = course.getname ()%> ID: <% = course.getid ()%> <%} catch (Exception E) {}% >