Use Hibernate to save Java objects to IBM DB2 universal database

zhaozj2021-02-16  99

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:

You will notice that the document type definition (DTD) file defined in DOCTYPE is present 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. tag is the basic tag in this XML file. This tag has two optional properties, but our app doesn't need them. See the Hibernate documentation for more information on these features. Elements represent a lasting Java class. It has an Name property that references the full qualification of the Java class we are mapped (separated by point). It also has a table attribute, this property references the database table (ie employee table) mapped to the class. The plugin does not generate a table property for us, so we will add it in the next section. element must also include a element to specify which field is the primary key of the database table and specifies how the primary key is generated. We will also discuss this issue in the next section. Hibernate documentation mentioned: " element declares a long-lasting JavaBean style property". This property is primarily used for the basic type or a string type instance variable. In our example, the employee's name must be represented by a element. 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 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: element NAME attribute reference) The name of the Javabean parameter in our class. The CLUMN Property references the column in the database. The class attribute of the column in the database is set to "assigned" means that we intend to specify the value of the primary key in the object. For automatic generating primary keys, There are other Hibernate options to choose from. You can find more information about these options in the Hibernate document. Now we need to further modify the code generated by the plugin and define each and Mark which columns will be mapped:

This modified documentation is as follows:

We will process the same processing on the department of department.hbm.xml . The final result is as follows:

Creating a data source and session We need to put an XML map 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.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

转载请注明原文地址:https://www.9cbs.com/read-11959.html

New Post(0)