Analysis and research of hibernate as data persistence layer

Source: Internet
Author: User
Tags extend implement key words sql net object model stub domain
Data SummaryThere are many ways to persist data in Java technology, and the persistence layer is one of the most important parts of Java applications. Based on the analysis of 3 kinds of persistence layer mainstream solution, this paper introduces the O-R mapping Open source project Hibernate, and introduces how to configure Hibernate environment in Web application development and use it to build an application.

   Key WordsHibernate, data persistence, JDBC, Ejb,jdo

   Introduction to Data persistence layer

Java EE's three-tier structure refers to the presentation layer (presentation), the Business Logic layer (Business Logic) and the infrastructure Layer (infrastructure), which is very classic, but in the actual project development method, Developers typically extend the three-tier structure to meet the specific requirements of some projects, and one of the most common extensions is to extend the three-tier system to a five-tier system, the presentation layer (presentation), the Control/Mediation layer (controller/mediator), the domain layer (domain), Data persistence layer (persistence) and the data source layer. It actually adds two layers to the three-tier architecture. The control/mediation layer is located between the presentation layer and the realm layer, and the data persistence layer is between the domain layer and the infrastructure layer. Because of the "impedance mismatch" between the two areas of object paradigm and relational paradigm, so the data persistence layer as a layer of the Java EE system is presented because it is possible to provide a successful enterprise-level mapping solution between the object-relational database, and to make the most of the differences between the two paradigms.

   three persistent layers of mainstream solutions

1. JDBC

Many developers use JDBC to develop database programs. In many cases, the DAO pattern is used in this way, and queries are made using SQL. Although this way you can make application code independent of the specific database vendor and database location, JDBC is a low-level way of database access, and JDBC does not support object-oriented database representations. The JDBC database represents a completely surrounding relational database model. Writing such code in the DAO of a large application is a very large amount of maintenance.

2. EJB

In the Java EE specification, two durable solutions are defined for EJBS: One is BMP and the other is CMP. Where CMP does not need to add SQL statements to the code. At present, the EJB CMP has been widely used in the application of Java EE. More notably, as the EJB specification evolved, CMP also contained some high-level relationships. However, the use of CMP is more complex and difficult to master for many developers. Also, not all cases are suitable for EJB use in the system, and it is time-consuming to understand the EJB specification very well. Before using EJB coding, let the expert understand the API, and then need to understand each container deployment of the technology to focus on. In addition, the performance and support of commercial containers are not very good in many cases.

3, JDO

JDO is a specification for storing Java objects, and the implementation of the JDO Specification 1.0 allows you to focus on designing the Java object model and then storing traditional Java objects in different layers of the enterprise Application architecture (Plain old Java Objects, referred to as POJOs), SQL operations in the JDOQL language. Some companies (including Sun) are attempting to design and implement JDO products based on the JDO specification, but they are not well implemented and performance optimization is poor.

   new solution for data persistence layer Hibernate

1, Hibernate introduction

Hibernate is an open source Object Relational mapping framework that gives JDBC a lightweight object encapsulation that allows Java programmers to manipulate the database with arbitrary object programming thinking. It not only provides a mapping between Java classes and data tables, but also provides a mechanism for querying and restoring data. Instead of using JDBC and SQL to manually manipulate a database, hibernate can significantly reduce the effort to manipulate the database. In addition, hibernate can use proxy mode to simplify the loading class process, which will greatly reduce the amount of code that utilizes hibernate QL to extract data from the database, thus saving development time and development costs hibernate can integrate well with a variety of Web servers or application servers, Almost all of the popular database servers are now supported.

2, Hibernate principle

Hibernate technology is essentially a middleware that provides database services. Its architecture is shown in Figure 1:


Figure 1


Figure 1 shows how hibernate works by using databases and other configuration files such as Hibernate.properties,xml mapping to provide data persistence services for applications.

Hibernate has a lot of flexibility, but at the same time its architecture is complex and offers several different ways to run. In lightweight systems, applications provide JDBC connections and manage transactions on their own, using a minimal subset of Hibernate, and in a comprehensive solution, all low-level jdbc/jta APIs are abstracted for applications, Hibernate will take care of all the details for you.

   use Hibernate to build an application

1. Configure Hibernate

The configuration file named Hibernate.cfg.xml is created in the SRC directory, and the hibernate configuration can be completed by adding its path to the applied classpath. The configuration file consists of properties that Hibernate uses to connect to the database, generate schemas, and obtain other specific database information. To reflect changes in the underlying database to the entire application, you only need to modify the property values within that file. The contents of the configuration file are as follows:

! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 2.0//en" "http:// Hibernate.sourceforge.net/hibernate-configuration-2.0.dtd ">

<session-factory>
<property name= "Hibernate.connection.driver_class" >com.ibm.db2.jdbc.app.db2driver </property>
<property name= "Hibernate.connection.url" >jdbc:db2:cipdb </property>
<property name= "Hibernate.connection.username" >admin </property>
<property name= "Hibernate.connection.password" >rubipass </property>
<property name= "dialect" >cirrus.hibernate.sql.db2dialect </property>
<mapping resource= "Com/ubipass/cip/data/event.hbm.xml"/>
</session-factory>
2. Create a mapping document

A mapping document is an XML document that defines persistent data and, when required, holds persistent fields, associations, subclasses, and agents for objects. You create a mapping document for each persistent object and for a file saved with the name Class_name.hbm.xml. In Class_name.hbm.xml class_name is the object's class name, and the following is the Event.hbm.xml content.

! DOCTYPE hibernate-mapping Public

"-//hibernate/hibernate Mapping DTD 2.0//en" "Http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"

<class name= "com.ubipass.cip.Event" table= "EVENTS"
<ID name= "id" column= "UID" type= "Long"
<generator class= "Increment"/>
</id>
<property name= "Date" column= "Event_date" type= "timestamp"/>
<property name= "title" column= "Event_title" type= "string"/>
</class>
The mapping document is compiled when the application is started, and it provides hibernate with the appropriate classes of persistent objects, their structure, which database table they should map to, and how to map information. Hibernate also uses these mapping documents to generate the corresponding database schema and stub Java classes, using the built-in devices Schemaexport and CodeGenerator respectively.

3. Generate stub Java classes for persistent objects

This task becomes much simpler after the mapping document has been created. The stub class is created using a hibernate built-in device CodeGenerator, which can be accomplished by executing a simple command. , the syntax for the command is as follows:

JAVA-CP Classpath Net.sf.hibernate.tool.hbm2java.CodeGenerator

Options Mapping_files

It provides the appropriate value for the classpath, options, and Mapping_files parameters. The following is a partial code of the stub Java class generated by mapping the document Event.hbm.xml.
 
Package Com.ubipass.cip
public class Event {
Private String title;
......
Event () {}
Public Long getId () {
return ID;
}
private void SetId (Long id) {
This.id = ID;
}
......
}
4. Generate Database Mode

To use the Hibernate schemaexport to generate the database schema, execute the following command after the appropriate value is submitted for the parameter:

JAVA-CP classpath net.sf.hibernate.tool.hbm2ddl.SchemaExport Options Mapping_files

This command provides the appropriate values for the classpath, options, and Mapping_files parameters. Figure 2 shows the shape of the pattern generated by the mapped document.


Figure 2
5. Initialize and run Hibernate code

To initialize and run hibernate, you need to take the following steps:

• Initialize and assemble the desired persistent object in the appropriate class;

• Use the Net.sf.hibernate.cfg.Configuration object to get the Net.sf.hibernate.SessionFactory object when the application is started;

• Invoke the Opensession () method on the Sessionfactory object to open the net.sf.hibernate.Session;

• Save the desired object and close the session.

The following code shows how to implement the steps above:

Initializing persistent objects

Event EV = new event ();
Ev.setdate ("1/4/2004")
Ev.settitle ("Hibernate startup");
try {
Start Hibernate
Configuration cfg = new Configuration (). addclass (Event.class);
Sessionfactory SF = Cfg.buildsessionfactory ();
Open session
Session Sess = Sf.opensession ();
catch (Hibernateexception e) {
E.printstacktrace ();
}

Save Product and Close session

Transaction t = sess.begintransaction ();
Sess.save (EV);
T.commit ();
Sess.close ();
   Summary

Hibernate is a powerful, O/R mapping scheme that can efficiently carry out database data to business objects. Hibernate drives the development of persistent objects based on the common Java object Model for mapping underlying data structures. By automatically extending the build of the persistence layer to a larger scope, Hibernate enables developers to concentrate on the business logic without distracting themselves from the cumbersome database logic, while providing a more rational approach to modular partitioning.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.