Use Hibernate to save Java objects to IBM DB2 universal database
Javid Jamae Independent Software Consultant, Jamae Consulting Texas Austin Kulvir Singh Bhogal IBM Software Services for WebSphere Texas Austin, October 2003
2003 International Business Machines Corporation. All Rights Reserved
Introduction Let us face realities, if you write a SQL statement in a manual application in an enterprise application, you will spend a lot of development time to update and maintain a persistent layer. If you can easily save the existing Java? Object (such as IBM? DB2? Universal Database?, Udb) isn't it good? 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 map We will use WebSphere? Studio 5.0 Application Developer configuration and a plug-in called Hibernator to develop applications, Hibernator can simplify some work of configuring Hibernate. Setting WebSphere Studio and Java project 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.dialect = cirrus.hibernate. Sql.db2diaract If you have not written the code to retrieve JDBC connections, then the top four parameters should be 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. Creating a database mode The properties file is now a database we have not created in the name of EMPL. Let us continue to complete this work forward. Let's 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 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 to recall, you read this document is to map the Java object to the database. Then we define these objects: Create a new class of Department: package com.ibm.hibernate_article; public class Department {private int departmentID; private String name; private String city; private String state;} Create a new class Employee:
package com.ibm.hibernate_article; public class Employee {private int employeeId; private String firstName; private String lastName; private String email; private Employee manager; private Department department;} for our newly created two classes:
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. Creating an XML mapping Since the Java class and database tables are ready, we 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. To generate an O / R mapping XML file with the Hibernator plugin, we must also do some edit work, but this view does not actually provide editing functions, it just generates .hbm.xml files. In this way, we will need to open the Employee.hbm.xml file in a regular file editor. Analysis Mapping file This plugin generates a file, the content is as follows:
XML Version = "1.0"?>
"In our example, the Employe class exists between the MANY-TO-ONE association between the Employe class and the Department class. Modifying the map. Our EMPLOYEID instance variable will map the EID column in the database. Because EID will become our primary key, so we Need to remove the Property element generated for the EmployeeID, and replace it with the ID element:
XML Version = "1.0"?>
XML Version = "1.0"?>
private SessionFactory sessionFactory; static {try {Datastore ds = Hibernate.createDatastore (); ds.storeClass (Employee.class); ds.storeClass (Department.class); sessionFactory = ds.buildSessionFactory ();} catch (Exception e) { Throw new runtimeException ("COULDN't 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. Operation Database Object This section describes how to write into the database, how to load into objects and how to update and query the database. Write to 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; session.flush (); session.Connection (). Commit (); session.close (); From the database load object load object is the identity of the object to transfer the object to memory The process. 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); session.close (); Update Database To update an object, you can create the object During the session, you can also do 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; 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.opensesis (); department dept = (department) session.load (Department) session.Load (Department); DePt.setName ("AdifferntName"); LATERSession.Flush (); session.connection (). Commit (); latersession.Close (); Query Database Query Database There are several ways. 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' "); Testing Since we have a session object and know how to do some operations, then we can write some on our simple object model. CRUD tests 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. Conclusion In this article, we only discuss 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/ Download Description File Type File Size Download Method Hibernate.zipzip5 KBHTTP
Page
About author
Javid Jamae is an independent software consultant who specializes in enterprise applications and software methods. You can contact Javid with javidjamae@yahoo.com. Kulvir Singh Bhogal work roles is a WebSphere consultant, implemented IBM e-commerce strategy in the United States. You can contact Kulvir through kbhogal@us.ibm.com.
IBM, DB2, DB2 Universal Database and WebSphere are trademarks or registered trademarks of IBM companies or other countries or regions. Java and all Java-based trademarks and logos are SUN Microsystems, Inc. trademark or registered trademarks in the US or other country or region. Other companies, products and service names may be trademarks or service marks from other companies. IBM copyright and trademark information