Headed: http://www-900.ibm.com/developerWorks/cn/dmdd/library/techarticles/0306bhogal/0306bhogal.shtml
introduction
Let us face realities, if you write the code of SQL statement in an enterprise application, you will spend a lot of development time to update and maintain persistence layers. This is not very good to easily save the existing JavaTM object to a relational database (such as IBM® DB2® Universal DatabaseTM, UDB)?
Fortunately, there is such a way. Object / Relational, O / R) Mapping Tool is some mature tools that map objects to rows in the relational database, which no longer requires complex persistence, and makes developers only need to write minimal SQL, in most cases no need to write any SQL.
Hibernate is an open source code published in accordance with the LGPL license, which is "Object / Relationship Persistence and Query Services for Java". In this article, we will show you how to use Hibernate to easily (a line SQL code does not write) to save the Java object to the DB2 database.
To demonstrate Hibernate's working mechanism, we will create a simple class model that consists of two classes: Employee and Department. For the sake of simplicity, an employee has a department, and the department has not been referenced by the employee. Refer to Figure 1 for class diagrams.
Figure 1. Employee / DepArtment class diagram
We will use WebSphere® Studio 5.0 Application Developer configuration and a plugin called Hibernator to develop applications, Hibernator can simplify some work to configure Hibernate.
Set up WebSphere Studio and Java projects
First, let us spend some time to prepare the elements needed by the experiment:
Create a new Java project in WebSphere Studio. Download Hibernate from http://sourceforge.net/projects/hibernate/. When writing this article, Hibernate's version is 1.2.4. Unzip the Hibernate compressed document obtained from the SourceForge, unzip the contents into a temporary directory. Import a JAR file named hibernate.jar to the base directory of the project. Import the following JAR files from the LIB directory in the Hibernate distribution package:
Commons-lang.jar command-collections.jar command-logging.jar XML-apis.jar Xerces.jar Adds Hibernate.jar to your Java build path (right-click Project -> Properties - > Java Build Path -> Libraries -> Add Jars ..., then point to Hibernate.jar you imported. Download the Hibernate Eclipse plugin from SourceForge (http://sourceforge.net/projects/hibernator/). You will see that this plugin makes it easier to synchronize an existing Java class and a Hibernate mapping file that defines our O-R mapping rules. The version of the plugin is 0.9.3 when writing this article. Unzip the compressed file of this plugin to the [WSAD 5 InstallDir] / Eclipse / PLUGINS / directory. To interact with DB2 UDB, we also need to import DB2 JDBC database drivers. Import a DB2JAVA.ZIP file in the C: / Program files / IBM / SQLLIB / JAVA / directory in the default. Be sure to add DB2JAVA.ZIP to classpaths. We have included some JUnit tests in the code included in this article. If you want to run these tests, you need to import the JUnit.jar file that is located in the [WSAD5InstallDir] / Eclipse/plugins/org.junit_3.7.0 directory. We must restart WebSphere Studio so that it can register our added plugins. Configuring hibernate.properties
In order to facilitate communication with DB2 UDB, we need to let Hibernate know some of our database properties. To do this, we will create a file called hibernate.properties, which must appear in the classpath of our application. In our example, we will put this property file into the basic directory of the project, which is included in the classpath. You may need to change the following attribute values for your own database settings.
Hibernate.Connection.driver_class = com.ibm.db2.jdbc.app.db2driver
Hibernate.connection.url = JDBC: DB2: EMPL
Hibernate.Connection.userName = db2admin
Hibernate.connection.password = db2admin
Hibernate.Dialev = Cirrus.hibernate.sql.db2diafor
If you have never have written code that retrieves JDBC connections, then the top four parameters should be very familiar with you. Hibernate.DiaLect property tells hibetnate We are using DB2 "dialect". Set this "dialect" allows Hibernate to enable some DB2-specific features in the default, so you don't have to set them manually.
Create a database mode
The above attribute file references the database called EMPL yet. Let us continue to complete this work forward. Let us go to the DB2 command line processor:
DB2 => CREATE DB EMPL
DB2 => Connect to EMPL User DB2Admin Using DB2Admin
In addition, we need to use some tables:
DB2 => CREATE TABLE Employee (EID INT NOT NULL PRIMARY KEY,
Firstname varchar (30) Not null,
Lastname varchar (30) Not null,
Email varchar (30) Not null,
Managereid int, departmentID int not null
DB2 => CREATE TABLE Department (
DepartmentID Int Not Null Primary Key,
Name varchar (30) Not null,
City varchar (30) Not null,
State varchar (30) Not null
Create JavaBeans to be mapped
Recall that you read this document is to map the Java object to the database. Then let's define these objects:
Create new class departments:
Package com.ibm.hibernate_Article;
Public class departments
{
PRIVATE INT DepartmentID;
PRIVATE STRING NAME;
PRIVATE STRING CITY;
PRIVATE STRING.
Create a new class Employee:
Package com.ibm.hibernate_Article;
Public Class Employee
{
Private Int EmployeID;
Private string dimstname;
PRIVATE STRING LASTNAME;
PRIVATE STRING Email;
PRIVATE EMPLOYEE MANAGER;
PRIVATE Department DEPARTMENT;
Two classes we have created newly created:
In the outline view, right-click the class name. Select Generate Getter and Setter .... Select all. Click OK.
Keep in mind that all setter and getter must exist, but their visibility is irrelevant. This way, if you need to maintain the constant object, you can set its status during constructing the object and set all the setter methods to private. In addition to any other constructor created, you must provide a default constructor; however, the visibility of the default constructor can also be set private. The SETTER and GETTER methods and the default constructor must exist because Hibernate follows the JavaBeans syntax and uses these method feature to last in the O / R mapping.
Create an XML mapping
Since the Java class and the database table are ready, we now need to define an O / R mapping. Hibernate implements this target by reading an XML file containing a mapped definition.
Let us first create mappings for the Employee class.
Open the Employee.java file in the editor. Click Window -> Show View -> Other -> Hibernator -> Hibernator (see Figure 2). Figure 2. Show Hibernator views in the Hibernator view, right-click, then click Save (Figure 3). Figure 3. Generate an O / R mapping XML file with the Hibernator plugin
We must also do some editing, but this view does not actually provide editing functions, it just generates .hbm.xml file. In this way, we will need to open the Employee.hbm.xml file in a regular file editor.
Analysis mapping file
The plugin generates a file, the content is as follows:
XML Version = "1.0"?>
"- // hibernate / hibernate mapping dtd // en"
"http://hibernate.sourceforge.net/hibernate-mapping.dtd">
clas>
hibernate-maping>
You will notice that the document type definition (DTD) file defined in DOCTYPE exists in the specified URL (ie http://hibernate.sourceforge.net/hibernate-mapping.dtd). If the mapping file exists in a classpath, Hibernate will always first reference it from there. Because the mapping file is in the hibernate.jar file, you will do not worry about importing it in your classpath. This file is used to define the valid tags allowed in the XML file.
Hibernate documentation mentioned: "
Many-to-one (multi-one) element is used to "the relationship model is a multi-to-one association with another long-lasting class. (it is actually a reference). "In our example, the Employee class is associated between the Employee class and the Department class. Modify mapping file
Our EmployeeID instance variable will be mapped to the EID column in the database. Because the EID will become our primary key, we need to remove the Property element generated for the EmployeeID, and replace it with ID elements:
id>
Now, we need to further modify the code generated by the plugin, and start to define each
In this way, the modified documentation is as follows:
XML Version = "1.0"?>
"- // hibernate / hibernate mapping dtd // en"
"http://hibernate.sourceforge.net/hibernate-mapping.dtd">
id>
clas>
hibernate-maping>
We will do the same treatment as DEPARTMENT.HBM.XML. The final result is as follows:
XML Version = "1.0"?>
"- // hibernate / hibernate mapping dtd // en"
"http://hibernate.sourceforge.net/hibernate-mapping.dtd">
id>
clas>
hibernate-maping>
Create a data source and session
We need to put XML mapping into some object representation, so Hibernate can use them. The specific practice is an instance of creating a Cirrus.Hibernate.DataStore class. Then we tell this DataStore instance as a given class store map information, the method is to call the StoreClass method and provide this method to the custom class Class object. The StoreClass method knows the use of the fully qualified class name to find the corresponding .hbm.xml mapping file.
After you have a DataStore object, we need to use it to build sessionFactory. This sessionFactory will be responsible for creating some Session objects. The Hibernate document defines the session as "Single-threaded, there is a short time, representing the conversation between applications and persistent storage". Session packaging JDBC connections, act as a factory of Transaction objects, and manages persistent objects in the application. The session can span multiple transactions, so it does not have to represent a working atomic unit as a matter.
Let us create a static initializer that will be responsible for creating a sessionFactory object. This static initializer will be loaded when the class is first referenced. After static loading this initializer, we will no longer need to reload the Employee and Department class mappings. Private sessionFactory sessionFactory;
STATIC {
Try
{
DataStore DS = Hibernate.createdTaStore ();
DS.StoreClass (Employee.class);
DS.StoreClass (Department.class);
SessionFactory = DS.BUILDSESSIONFACTORY ();
}
Catch (Exception E)
{
Throw New RuntimeException ("COULDN 'Get Connection");
}
}
In the above code, the DataStore object acquires an instance of SessionFactory by calling the buildsessionFactory method. If you do not provide any parameters to the buildsessionFactory method, it will find the default properties file (ie, the Hibernate.properties files you created in front) in the runtime class path. Another way is that if this control is required in the code, you can pass the Properties object to the buildsessionFactory method.
After the static initializer initializes the SessionFactory object, we can call the OpenSession () method. This static method will return a new session object for us. If you do not provide parameters when you call OpenSession, SessionFactory will automatically manage the Connection. Many connection parameters (such as the size of the pool, statement cache, and idle time) can be configured via parameters (or supplied to SessionFactory) through the parameters in the hibernate.properties file. See the Hibernate documentation for more details.
If your program already has an existing connection management infrastructure, you can provide a connection to the OpenSession (Connection Con) method, and Hibernate will use the connection you provided.
Operating database objects
This section describes how to write into the database, how to load objects from the database and how to update and query the database.
Write into the database
To write to the database, we will open a new session using the SessionFactory object. Then we will create an object that you want to hold and save it to the session. Next, we refresh the (FLUSH) session, call submits (Commit), and close the (close) session.
The refresh session will force Hibernate to synchronize the data from the memory and the database. Hibernate will automatically refresh regularly, but cannot guarantee when Thus, we explicitly refresh the data in memory to the database, ensuring that the data is immediately written to the database.
Before shutting down the session, you must also ensure that the database connection is submitted.
Session session = sessionFactory.openSession ();
Department = new department ();
Department.SetCity ("austin");
Department.SetState ("TX");
Department.setname ("IBM Global Services"); Department.SetDepartmentId (211);
session.save (department);
Session.flush ();
Session.connection (). commit ();
session.close ();
Enter object from database
Load object is the process of using an object to transfer objects to memory. This is different from the query object we discussed in the query database.
In order to load objects from the database, we also need a session. We also need to be able to load the primary key of the object. For example, the example we have written earlier, if you want to install the DepartmentMent back to the object, we can call the session.low method with the Class object representing the Department, and our primary key is "211".
Session session = sessionFactory.openSession ();
Department dept = (department) session.load (Department.class, New Integer (211));
session.close ();
Update database
To update an object, you can do it in the session of the object or in a completely different session. Updating objects in the same session is easy; just modify the status of the object. To update the object in a different session, you must load (or query) the object and then update it.
Same session
session.save (department);
Session.flush ();
Department.SetName ("newname");
Session.flush ();
Different sessions
//first session
Department department = new department ();
Department.SetDepartmentId (211);
Department.setname ("Somename");
.
. // set Other stuff on Department
.
session.save (department);
Session.flush ();
Session.connection (). commit ();
session.close ();
// later session
LATERSESSION = sessionFactory.openSession ();
Department dept = (department) session.load (Department.class, New Integer (211));
DePt.setName ("Adifferentname");
Latersession.flush ();
Session.connection (). commit ();
Latersession.Close ();
Query database
There are several ways to find the database. The simplest way is to use the session.find method. You must use Hibernate to provide a query for SESSION.FIND using Hibernate simple but powerful inquiry query language. The following example demonstrates a very simple query. If you want more complex queries, see the Hibernate document for more details.
Department department = new department ();
Department.SetDepartmentId (211);
Department.setname ("Somename");
.
. // set Other stuff on Department
.
session.save (department);
List list = session.find ("from dept in class com.ibm.hibernate_article.Department where dept.city = 'austin');
carry out testing
Since we have a session object and know how to do some operations, we can write some CRUD testing on our simple object model to see the actual operation of Hibernate. This is a much better test method than JUnit. You can view the HibernateTest.java test case in the source code attached to this article.
Conclude
In this article, we discussed how to use Hibernate. We introduce the Hibernate API in the context of several Pojo (Plain Old Java Object, traditional Java object). However, pay attention to a wide range of Hibernate API covers more advanced themes such as One-To-Many (one-to-many) mapping, transaction, and collection. Since you have "involved" Hibernate, it should be more comfortable to explore how to use open source products in programming work.
We used Hibernate in some projects, and some obstacles were encountered. We found that the Hibernate Forum on SourceForge is indispensable to answer our questions. In this forum, Hibernate's main developers are very active, and they almost answer all posts.
The website of the forum is: http://sourceforge.net/forum/forum.php? Forum_id = 128638
HiBernate web page URL: http://hibernate.bluemars.net/