|
Developer: J2EE & Web Services
Integrating Hibernate with JSF in JDeveloper 10.1.3
by Deepak Vohra
Learn how to create tables and add, retrieve, update, and delete data using the winning combination of Oracle JDeveloper, JBoss Hibernate, and JavaServer Faces (JSF)
JBoss Hibernate is a popular open source, object-relational persistence and query service for Java. It is commonly used by J2EE developers for generating tables for a database application; adding data to the tables; and retrieving, updating, and deleting table data. JBoss Hibernate also provides classes for Ant build tasks that may be integrated into an Ant build file.
In this tutorial, you will integrate Hibernate with the Oracle JDeveloper 10.1.3 IDE and Oracle Database 10g to develop an object-relational application. Keep in mind that Oracle TopLink is Oracle's recommended object-relational mapping (ORM) solution and that TopLink can take advantage of the Oracle Application Server platform in ways that JBoss Hibernate clearly cannot. But for those developers who are interested in using the latter in conjunction with Oracle JDeveloper, this tutorial will be helpful.
Furthermore, in contrast to Hibernate's code-centric approach, the integration of TopLink and JDeveloper provides visual, declarative ORM. (View demo.) Using TopLink for ORM will also allow you to leverage the Oracle ADF framework to simplify the building of your view and controller layers on top of the TopLink business services layer.
Overview
The database persistence Hibernate provides is based on a mapping file and a database properties file. The mapping file (an .hbm.xml file) specifies the database schema and the table(s) for the database application. The mapping file also specifies the Java classes for database persistence, the different fields and field types in the Java objects, and the corresponding database table columns and column types. The tables and Java classes may be generated from the mapping file or before you develop the Hibernate application. The database properties file (a hibernate.properties file) specifies the database, the JDBC driver, and the connection URL for the database applications.
The Ant task classes net.sf.hibernate.tool.hbm2java.Hbm2JavaTask and net.sf.hibernate.tool.hbm2ddl.SchemaExportTask are used to map the mapping file to database table(s) and the Java classes. The Java classes are subsequently used to add, retrieve, update, and delete data in the database tables.
In this tutorial, you will map an example mapping file, Catalog.hbm.xmlconsisting of properties for a journal catalogto a database table, OE.Catalog, and to a Java class, Catalog.java.
Preliminary Setup
The Hibernate API classes are required for integrating Hibernate with JDeveloper.
- Download the JBoss Hibernate 2.1.8 production and JBoss Hibernate Extension 2.1.3 zip files, and extract the files to an installation directory.
- Download and install Oracle JDeveloper 10g (10.1.3).
- Download and install Oracle Database 10g, and create a database instance including the sample schemas.
Integrating JBoss Hibernate Libraries
In this section, you integrate the Hibernate JAR files required to develop a JBoss Hibernate application into a JDeveloper 10g project. First, select File -> New in the JDeveloper IDE. In the New Gallery frame, select General -> Workspaces from the listed categories and select Application from the listed items. Specify a application name and directory name in the Create Application frame. Select No Template in the Application Template field. Specify a project name in the Create Project frame. A Hibernate workspace and project get added to the Applications - Navigator.
 | | Figure 1. Hibernate Project |
Next, add the libraries required to generate a Hibernate application to the project. Select the Hibernate project node in the Applications - Navigator. Select Tools -> Project Properties. In the Project Properties frame, select the Libraries node. Click on Add Library to create a new library. In the Add Library frame, click on New. In the Create Library frame, specify Hibernate in the Library Name field and click on Add Entry. In the Select Path Entry frame,
select the hibernate2.jar file and click on Select. The selected JAR file gets added to the Class Path node in the Create Library frame. Click on OK in the Create Library frame and in the Add Library frame. The Hibernate library gets created and added to the Libraries frame.
Similarly, create libraries for the other JAR files required for a Hibernate application. The libraries created and the corresponding JAR files are listed in Table 1.
Table 1.JBoss Hibernate Project Libraries
| Project Library | Description | JAR/Zip File |
| Hibernate-Extensions | The hibernate extension classes including the net.sf.hibernate.tool.hbm2java.Hbm2JavaTask class. | <Hibernate>/tools/hibernate-tools.jar |
| Hibernate | The Hibernate API classes including the net.sf.hibernate.tool.hbm2ddl.SchemaExportTask class. | <Hibernate>/hibernate-2.1/hibernate2.jar |
| Hibernate-Lib | The auxiliary Hibernate classes. |
- <Hibernate>/hibernate-2.1/lib/dom4j-1.4.jar
- <Hibernate>/hibernate-2.1/lib/commons-logging-1.0.4.jar
- <Hibernate>/hibernate-2.1/lib/commons-collections-2.1.1.jar
- <Hibernate>/hibernate-2.1/lib/ehcache-0.9.jar
- <Hibernate>/hibernate-2.1/lib/cglib-full-2.0.2.jar
- <Hibernate>/hibernate-2.1/lib/jta.jar
|
| Oracle JDBC | The Oracle database JDBC classes.
The Oracle JDBC library is preconfigured in the JDeveloper IDE.
Delete orai18n.jar from the <JDeveloper 10.1.3>\jdbc\lib directory. | classes12.jar |
| Properties | The directory in which the JBoss Hibernate properties file is copied. To add a Directory select the Add Directory button instead of the Add Library button. | <Hibernate>/properties |
| Classes | The directory in which the compiled Java classes are generated. | <Hibernate>/classes |
In Table 1, <Hibernate> is the directory in which the JBoss Hibernate JAR files are installed. <JDeveloper 10.1.3> is the directory in which JDeveloper 10.1.3 is installed. The libraries created are listed in the Libraries frame.
 | | Figure 2. JBoss Hibernate Project Libraries |
Developing JBoss Hibernate Mapping and Properties Files
The mapping file (an .hbm.xml file) and the properties file (a hibernate.properties file) form the basis of a JBoss Hibernate application. The mapping file consists of class definitions. Each class definition consists of a set of properties to be mapped to a Java class and a database table. The field and column types and additional characteristics of the columns, such as length, not-null, and unique, are also specified with the properties. Some of the frequently used tags in the mapping file are listed in Table 2.
Table 2.JBoss Hibernate Mapping File Elements
| Tag Name | Description | Attributes | Subelements |
| hibernate-mapping | The root element | schema, package | class |
| class | Specifies the class definition for mapping a Hibernate Java class to a database table | table, schema | id, property, set, list |
| Id | Required element in a class definition | column, type, length | column, generator |
| property | Specifies a class property that corresponds to a table column and a Java class field | type, column, length, not-null, unique | column |
The example mapping file in this tutorial consists of a class and class properties for a journal catalog. The example mapping file, Catalog.hbm.xml, follows:
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="example.hibernate.Catalog" table="OE.CATALOG">
<id name="id" type="int" column="CatalogId">
<generator class="native"/> </id>
<property name="journal" type="string"/>
<property name="publisher" type="string"/>
<property name="edition" type="string"/>
<property name="title" type="string"/>
<property name="author" type="string"/>
</class>
</hibernate-mapping>
The element <generator class="native"/> is required in the <id> element to generate Java classes from the mapping file.
The properties file, hibernate.properties, specifies the database configuration for the Hibernate application. The properties file is a text file with properties specified in <property>=<value>. The required properties of a hibernate.properties file are listed in Table 3.
Table 3.JBoss Hibernate Properties
| Property | Description |
| hibernate.connection.username | Username for logging in to the database. |
| hibernate.connection.password | Password for logging in to the database. |
| hibernate.connection.driver_class | Driver class for connecting with the database. |
| hibernate.connection.url | Connection URL for connecting to the database. |
| hibernate.dialect | The dialect for the database. For the Oracle database, specify net.sf.hibernate.dialect.OracleDialect. |
In the hibernate.properties file for the example application in this tutorial, the Oracle database example schema OE is specified for the username property. The Oracle Thin Type 4 driver is used with the driver class as oracle.jdbc.driver.OracleDriver. The hibernate.properties file for the Oracle database is shown below:
hibernate.connection.driver_class=oracle.jdbc.driver.OracleDriver
hibernate.connection.url=jdbc:oracle:thin:@<Host>:<Port>:<DB>
hibernate.connection.username=OE
hibernate.connection.password=
hibernate.dialect=net.sf.hibernate.dialect.OracleDialect
Generating Java Classes and a Database Table
In this section, you generate Java classes from the example mapping file (Catalog.hbm.xml) and generate an Oracle database table from the mapping file and the properties file (hibernate.properties). The classes to generate the mapping Java classes and the database table are run with a build.xml file. The JBoss Hibernate API provides the net.sf.hibernate.tool.hbm2java.Hbm2JavaTask task class for generating Java classes from an hbm.xml mapping file and the net.sf.hibernate.tool.hbm2ddl.SchemaExportTask task class for generating a database table from a mapping file.
First, create an Ant build file in JDeveloper 10g. Select File -> New. In the New Gallery frame, select General -> Ant. From the listed items, select Empty Buildfile.
In the Create Ant Buildfile dialog box, specify a filename, build.xml, and a directory name for the build file. A build.xml file is added to the Hibernate project in the Applications - Navigator.
The example build.xml file consists of targets to
- Generate Java classes from the mapping file
- Compile the Java classes
- Generate a database table from the mapping file and the hibernate.properties file
Structure of the build.xml file. Add the <project/> tag, which specifies the project name, the default target, and the basedir. Add build file properties that correspond to JBoss Hibernate directories. The directories are specified relative to the base directory, which is specified in the basedir attribute of the project element. The properties in the example build.xml are listed in Table 4.
Table 4. build.xml Properties
| Property | Value | Description |
| src.dir | src | The directory in which the Java classes from the mapping file are generated |
| classes.dir | classes | The directory in which the compiled Java classes are generated |
| hibernate | hibernate-2.1 | The directory that includes the hibernate2.jar file and the Hibernate subdirectories |
| hibernate.mappings | mappings |
The directory for the mapping file |
| jdbc | C:\oracle\product\10.1.0\Db_1\jdbc | The directory that includes the classes12.jar file |
| hibernate.extensions | tools | The directory that includes the hibernate-tools.jar file |
| hibernate.properties | properties | The directory that includes the hibernate.properties file |
In the build.xml file, add a <path/> element to specify the classpath for the build.xml file targets. The classpath includes the hibernate2.jar, hibernate-tools.jar, classes12.jar, and the auxiliary JBoss Hibernate and Hibernate-extensions JAR files.
The init target generates the directories for the build.xml file.
The javaGenerator target generates Java classes from the Hibernate mapping file with the net.sf.hibernate.tool.hbm2java.Hbm2JavaTask class.
The compile target compiles the Java classes generated from the mapping file.
The schemaGenerator target generates the database table from the mapping file and the properties file with the net.sf.hibernate.tool.hbm2ddl.SchemaExportTask class.
Download the example build.xml file from this article's support files; then build the targets in the build.xml file. Right-click on the build.xml file node, and select Run Ant.
 | | Figure 3. Run Ant |
In the Run Ant frame, select the schemaGenerator target. The targets preceding the schemaGenerator target also get built as the targets are specified in the depends attribute.
 | | Figure 4. schemaGenerator Target |
A Java class corresponding to the mapping file gets generated. The Java class has getter and setter methods for each of the class properties specified in the mapping file. (Catalog.java, the Java class generated with the Hibernate mapping file, is available in the support files.) A database table, specified in the table attribute of the class element in the mapping file, also gets generated. The structure of the OE.Catalog table gets displayed in the output from the build.xml file.
 | | Figure 5. Output from build.xml |
In the following section, you add, retrieve, update, and delete table data with the Java class generated from the mapping file and the hibernate.properties file.
Adding and Updating Table Data with Hibernate
In this section, you develop a middle-tier Java application to add, update, and delete data in the table generated from the mapping file, Catalog.hbm.xml. The Java application is not the Java class generated from the mapping file. The Java application integrates the Java class generated from the mapping file, the mapping file, and the properties file to provide a database-persistence and query service.
First, add libraries for the classes directory and the properties directory to the JBoss Hibernate project. The HibernateClass and HibernateProperties libraries are listed in Table 1. Next, copy the mapping file, Catalog.hbm.xml, to the package in which the Catalog.class is located, the example.hibernate directory.
Select File -> New, and in the New Gallery frame, select General -> Simple Files. From the listed items, select Java Class. In the Create Java Class frame, specify a class name and a class package. A Java class gets added to the Hibernate project.
 | | Figure 6. HibernateDB.java Java Class |
In the Java application, import the Hibernate API classes.
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;
Import the Java class that was generated from the mapping file.
import example.hibernate.Catalog;
Create a Catalog class object, and set values for the different fields of the Java class with the setter methods.
Catalog catalog=new Catalog();
catalog.setId(new Integer(1));
catalog.setJournal("Oracle Magazine");
catalog.setPublisher("Oracle Publishing");
catalog.setEdition("Sept-Oct 2004");
catalog.setTitle("Tracing SQL in Oracle Database 10g");
catalog.setAuthor("Kimberly Floss");
The main runtime interface between a Java application and Hibernate is net.sf.hibernate.Session. Create a net.sf.hibernate.cfg.Configuration object to specify the properties and mappings files for the SessionFactory object from which Session instances are generated.
Configuration config=new Configuration();
Specify the mapped class, Catalog.class, for the configuration.
config.addClass(example.hibernate.Catalog.class);
The mapping file, Catalog.hbm.xml, which is copied to the same directory as the mapped Java class, gets configured with the Configuration object. The hibernate.properties file in the classpath of the Hibernate application gets configured as the properties file for the Configuration object. Create a SessionFactory object from the Configuration object.
SessionFactory sessionFactory=config.buildSessionFactory();
First, you add data to the database table that was created with the hibernate.mapping file and the hibernate.properties file.
Create a database connection, and open a session.
Session sess = sessionFactory.openSession();
Begin a transaction with the database.
net.sf.hibernate.Transaction tx = sess.beginTransaction();
Store the Catalog object that was created earlier.
sess.save(catalog);
Commit the transaction.
tx.commit();
The values specified in the Catalog object get stored in the database table.
Next, you retrieve the data stored in the database table.
Create a query to select data from the table. The query is defined in Hibernate Query Language (HQL) syntax, which is similar to SQL syntax.
String query="from example.hibernate.Catalog";
If the select clause is not specified in the query, all of the fields selected in the from clause are selected from the mapped class. The from clause is specified with the mapped Java class, example.hibernate.Catalog, not the database table. The Java-class-object-to-database mapping is performed by the mapping file and the properties file.
Open a session for the database transaction.
Session sess = sessionFactory.openSession();
The find method of the Session object returns a list for the specified query.
List list=sess.find(query);
To retrieve values from the list, cast the list items to the object type, Catalog.
Catalog catalog=(Catalog)list.get(i);
Next, you update table values with the Java application.
Create a query to select data from the table. For example, select the Catalog object for the Nov-Dec 2004 edition.
String query="from example.hibernate.Catalog as catalog where catalog.edition='Nov-Dec 2004'";
Open a session with the database.
Session sess = sessionFactory.openSession();
Begin a transaction with the database.
Transaction tx = sess.beginTransaction();
Obtain the list for the query.
List list=sess.find(query);
Catalog catalog=(Catalog)list.get(0);
As an example, modify the value of the Publisher field.
catalog.setPublisher("Oracle Magazine");
Update the table with the saveOrUpdate method.
sess.saveOrUpdate(catalog);
Commit the transaction.
tx.commit();
Next, you delete a table row with JBoss Hibernate.
Create a query that selects the table row to delete.
String query="from example.hibernate.Catalog as catalog where catalog.edition='Nov-Dec 2004'";
Open a session with the database.
Session sess = sessionFactory.openSession();
Begin a transaction with the database.
Transaction tx = sess.beginTransaction();
Delete the row selected with the query, with the delete method.
sess.delete(query);
Commit the transaction.
tx.commit();
The example Java application, HibernateDB.java, has the addData method to add data, retrieveData method to retrieve data, updateData method to update data, and deleteData method to delete data. HibernateDB.java is available in the support files.
To run the Java application, right-click on the application node and select Run.
Integrating JBoss Hibernate with JSF
JDeveloper 10.1.3 supports Java Server Faces (JSF) technology. The JSF technology provides user interface (UI) components for developing Web applications. In this section, the JBoss Hibernate Java application developed in the previous section is integrated with UI components in a JSF JSP page. To integrate the Java application with JSF, create a JSF page to access the middle-tier Java application.
Modify the Java class HibernateDB.java; add the setData and getData methods. The getData method has a String parameter that specifies a HQL query and returns a String array that consists of a row
of table data for the query. (The return type of the getData method may also be set to
java.util.List.) The Java implementation class HibernateDB_class.java is available in the support files
Next, Create a JSF JSP page to access the middle-tier Java application. Select File -> New -> Web Tier -> JSF, and select JSF JSP page from the listed items.
 | | Figure 7. New JSF JSP Page |
In the Create JSF JSP frame, specify a name, select the default settings, and click on Next. Select the default settings in the HTML Options frame, and click on Next. Click on the Finish button in the Finish frame. A JSF JSP page gets added to the project. An MBean class, example.hibernate.backing.Catalog.java, and the JSF configuration file faces-config.xml also get generated for the JSF page. On the JSF JSP page, select CSS in the Components palette, select JDeveloper in the CSS list, and add the selection to the JSF JSP page.
Add a Heading 3 to the JSP page. Select JSF HTML in the Components palette, and add Input Text to the JSP page.
 | | Figure 8. Adding Input Text to JSF JSP Page |
Select and add a command button from the JSF HTML Components palette to the JSF page.
 | | Figure 9. Adding a Command Button to the JSF Page |
Add an output label and output text from the Components palette to the JSF page. In the Property Inspector, set the text on the command button to Query.
 | | Figure 10. Setting Command Button Text |
Set the value of the output label to CatalogID. Similarly, add output labels and output text fields for Journal, Publisher, Edition, Title, and Author.
Next, add event code to the commandButton_action method, the method that gets invoked when the Query button is clicked on in the JSP. Double-click on the Query button. The commandButton_action method in the example.hibernate.backing.Catalog.java class appears. In the commandButton_action method, access the middle-tier Java application, HibernateDB.java.
HibernateDB myPort=new HibernateDB();
With the HQL query specified in the Input Text field on the JSF JSP page, invoke the getData method of the HibernateDB object. A String[] array that has the data from the Catalog database table gets returned by the getData method.
String[] result=new String[6];
result=myPort.getData((String)inputText1.getValue());
Retrieve the values from the result array, and set the values in the OutputText fields.
outputText1.setValue(result[0]);
outputText2.setValue(result[1]);
outputText3.setValue(result[2]);
outputText4.setValue(result[3]);
outputText5.setValue(result[4]);
outputText6.setValue(result[5]);
Here is the commandButton_action method:
public String commandButton_action()
{
// Add event code here...
HibernateDB myPort=new HibernateDB();
String[] result=new String[6];
result=myPort.getData((String)inputText1.getValue());
outputText1.setValue(result[0]);
outputText2.setValue(result[1]);
outputText3.setValue(result[2]);
outputText4.setValue(result[3]);
outputText5.setValue(result[4]);
outputText6.setValue(result[5]);
}
Next, run the JSF JSP page. Right-click on the Catalog.jsp node, and select Run.
The JSF JSP page appears in the default browser.
Specify an HQL query ( "from example.hibernate.Catalog where edition='Sept-Oct 2004'") in the Input Text field to select a row of data, and click on the Query button. The HQL query selects the Catalog table row for the Sept-Oct 2004 edition.
The result of the query appears in the JSF JSP page.
 | | Figure 11. Hibernate Query Output in the JSF Page |
As discussed in this section, integrating the Hibernate application with a JSF page lets you access the application with the UI components provided by the JSF technology.
Generating a JSF Data Table
The output generated from a JBoss Hibernate query in the previous section is displayed with the JSF components Output Label and Output Text. In this section, you generate a data table from the output of a JBoss Hibernate query with the Data Table Wizard. A data table is a UI component for displaying a data collection in a table. To generate a data table from a query,
- Create a client class for the middle-tier Java application.
- Create a JSF page.
- Create a Managed Bean (MBean) from the client class.
- Add a data table to the JSF page.
First, create a bean class for the middle-tier Java application, HibernateDB.java. The bean class consists of getter and setter methods for the header and component values of the data table you will generate in this section. Add a MyWebService1SEI interface for the bean class. (The bean class, HibernateDB_bean.java, and the interface for the bean class, MyWebService1SEI.java, are available in the support files.) Generate a Web service from the bean class and interface. In the bean class node, select Create J2EE Web Service.
 | | Figure 12. Create Web Service |
In the Select J2EE Version frame, select "Create J2EE 1.4 (JAX-RPC) web services."
Next, generate the client class for the Web service. Right-click on the Web service node, and select Generate Web Service Stub/Skelton. A client class for the Web service gets generated. In the client class, add a method that returns a collection of data retrieved with an HQL query. The client class, MyWebService1PortClient.java, is available in the support files.
 | | Figure 13. Generate Client class |
Add a JSF JSP page to the JBoss Hibernate project. Select Categories -> Web Tier -> JSF in the New Gallery frame, and select JSF JSP from the listed items. Specify a JSF JSP filename, and click on Next. In the Tag Libraries frame, the JSF tag libraries are preselected. Click on Next. Select the default HTML options, and click on Next. Click on Finish. Create an MBean from the client class for the JSF page data table. Select the faces-config.xml node and the Overview frame. Click on New to add a managed bean.
 | | Figure 14. Adding a Managed Bean |
Specify a managed bean name, and specify the client classexample.hibernate.proxy.MyWebService1PortClientin the Class field. Select "request" as the scope.
 | | Figure 15. Create Managed Bean |
A managed bean gets added to the Managed Beans list.
 | | Figure 16. Managed Beans |
On the JSF page, select JSF HTML in the Component palette and add a data table to the JSF page.
 | | Figure 17. Adding a JSF Data Table |
The Data Table Wizard gets started. In the Binding frame, select "Bind the Data Table Now."
 | | Figure 18. Data Table Wizard |
Next, bind the data table with a data collection. In the Bind Data Table frame, the value field specifies the data collection (java.util.Collection) from which a data table is to be generated. The Class field specifies the data class, and the Var field specifies the variable for a row of data in the data collection. Click on Bind to select a data collection.
 | | Figure 19. Binding Data Table with a data collection |
In the Expression Builder frame, select the managed bean that was created from the client class for the middle tier of the Hibernate application. The dataList method of the client class returns a java.util.List collection of data. Add the dataList node to the Expression frame with the > button.
 | | Figure 20. Expression Builder |
In the Var field, specify a variable for a row of data in the data collection and click on Next.
 | | Figure 21. Bind Data Table |
In the Header and Row Data frame, the header values and the component values for the data table are listed. Modify the order of the data table components to match the columns in the database table, and click on Next.
 | | Figure 22. Header and Row Data |
In the Finish frame, click on Finish. The header values for the data table get added to the data table.
 | | Figure 23. Data Table Header Values |
To generate the data table, right-click on the JSF JSP and select Run.
 | | Figure 24. Run JSF JSP Page |
The data table generated with the HQL query specified in the client class gets displayed.
 | | Figure 25. JSF Data Table |
Congratulations; you have just built an object-relational application using Oracle JDeveloper and JBoss Hibernate.
Deepak Vohra (dvohra09@yahoo.com) is a Sun Certified Java 1.4 Programmer and Oracle Database 10g Administrator Certified Associate.
|