IBM WebSphere Developer Technical Journal: Develop Hibernate applications for WebSphere Application Server

xiaoxiao2021-03-06  72

Level: Intermediate

SUNIL PATIL

(SUNILPATIL@in.ibm.com) Software Engineer, IBM 2004 November

Step step by step Step step by step, using WebSphere® Application Server connection and transaction management when creating a Hibernate application.

Get the products and tools used herein. If you are developerWorks subscribers, you will have a single user's license to use WebSphere Application Server and other DB2®, Lotus®, Rational®, Tivoli® products, including Eclipse-based WebSphere. Studio IDE - to develop, test, evaluate, and demonstrate your app. If you are not a subscriber of developerWorks, you can now be scheduled.

Preface Hibernate is a popular open source object relationship mapping tool running in a Java environment. This technology can be presented from an object model to a relational data model with SQL-based mode, and the object relationship mapping references this technology. This means that Hibernate provides multi-level abstract methods when interacting with the database.

Hibernate is very flexible and supports multiple methods. In one case, using the minimum subset of the Hibernate API, it can only be used to interact with the database, in which case the application must provide yourself to provide yourself and manage your own transactions; such as the middleware such as WebSphere Application Server These functions can be implemented. In another case, even if you do not run the middleware, you can also use the full version of Hibernate. In this case, you provide the database configuration information to Hibernate, then it is not only for you to create and manage connections, but also They can also manage them by delegating the transaction to the base database.

With Hibernate, you need to create a Java class to describe the tables in the database and map the instance variables in the class to the columns in the database. At this time, as you think, you can call Hibernate to select, insert, update, and delete records in the underlying table instead of creation and executing queries yourself.

Hibernate architecture has three main components:

Connection Management Because the overhead of the database is turned on and off when the database interaction is very expensive, you should put your database connections in the pool and can be reused. Transaction Management When performing multiple queries in a batch; the result may be that all queries are successful, or all failures. Object Relations Maps In this section, specific Java object hibernate is inserted or updated; for example, when you pass an object's instance to the session.save () method, Hibernate will read the status of this object instance variable, and create And executive queries. In the case where the query is selected, the object of the description result set will be returned.

Hibernate is very flexible and provides multiple ways to use these components:

"Lite" architecture is used when you just want to use the Hibernate object relationship mapping component. In this case, you need to achieve your own connection and transaction management, for example, with WebSphere Application Server. "Full Cream" architecture is used when you want to apply all three Hibernate components. Hibernate can manage you, but you must provide information such as driver class, username, password, and other connection information via XML configuration. When you manage your transaction, you can call start, submit, and rollback methods on the Hibernate object.

Hibernate is a very good tool when it comes to an object relationship mapping, but it lacks the necessary performance and ability in connection management and transaction management. Fortunately, we can combine Hibernate's object relationship map with WebSphere Application Server connection and transaction management, create powerful applications. This article assumes that you already have the basic knowledge of Hibernate, Enterprise JavaBean (EJB) components, and Struts. If you just get in touch with Hibernate, please refer to the object-related object relationship map without an object, this article discusses how to use Hibernate to implement simple insert, update, and delete operations.

About the sample application In order to implement this article, we will create a simple Struts web application that allows users to insert new records to the Contact table. Our sample applications will use AddContact.jsp to receive the user's input. AddContactAction.java is an activity class that will use Hibernate to insert a new contact to go to the database. If the contact is successfully inserted, the user is redirected to Success.jsp, which will display the details of the latest inserted contacts. If you have encountered a problem, you will display the Failure.jsp page.

Figure 1. Example application plugging page

When using Hibernate, we will create an instance application, this program uses Hibernate's own connection pool and transaction management (also please refer to the "Full Cream" architecture):

Create a Struts application that can be implemented using WebSphere Studio Application Developer (referred to as Application Developer) or by importing Struts-Blank.war inside the Struts release. Create a must-have JSP page and activity class for the sample application, you can also import from download file Sample1.zip. Download Hibernate binary from the Hibernate website: copy hibernate2.jar and JAR library files (Dom4j.jar, xmlapi.jar, and other) to the web-inf / lib directory. Create a Contact.java class and create a member variable for each column in the Contact. Each field should create a getter and setter method. Also need to create a contact.hbm.xml file, this file will map the instact.java instance variable to the column of the Contact table. Create hibernate.cfg.xml in your source code root directory. This file saves the application level configuration information for Hibernate, just as shown in Listing 1. Listing 1

COM.ibm.db2.jdbc.app.DB2Driver jdbc : db2: SAMPLE db2admin db2admin true net.sf.hibernate.diaract.db2diaalect CREATE-DROP in this file You will notice if we need to open the connection with pure JDBC, we must specify the same information here:

Hibernate.Connection.driver_class is our JDBC drive class we have to use. Hibernate.connection.password and hibernate.connection.username are trust in the database. Hibernate.Connection.URL is the JDBC URL used to connect to the database. The DiaLect property determines the special language used when getting the query. Hibernate supports a special language of all popular relational database management systems (RDBMs), such as DB2 or OracleTM. Therefore, for example, if you use Oracle during the development process, you want to transfer to DB2 during production, just need to change the hibernate.cfg.xml file. Hibernate.hbm2ddl.Auto can be used to indicate hibernate. When we initialize it, create DDL from the mapping file for our application, and create these tables and sequences in the database. The value of CREATE-DROP means that the table created by hibernate will be deleted when Hibernate is closed. Contact.hbm.xml is a map of the Contact target. If you have multiple tables, you can create multiple mapping files (one for each table), and add multiple elements, you can also create multiple mappings in a file, and add a element. In our application, we will read the values ​​entered by the user and insert a new record into the Contact table. AddContactAction.java class performs this method: Listing 2

.. SessionFactory sessionFactory = new Configuration () configure () buildSessionFactory (); Session session = sessionFactory.openSession (); // Create new instance of Contact and set values ​​in it by reading them from form object Contact contact = new Contact () Contact.setfirstname (String) Contactform.Get ("firstname")); session.save (contact); // actual contact insertion will happen at this step session.flush (); session.close (); by specifying New CONFIGURATION (). Configure (). BuildSessionFactory () is initialized hibernate. Hibernate will try to locate /Hibernate.cfg.xml in the root directory. If discovered, it will load it and provide us to a SESSIONFACTORY, we can use it to interact with Hibernate. Session (session) indicates a logical interaction; in a session you can activate multiple queries. In order to insert a contact, create a new instance of a Contact class. By calling the setter method to set the value of each field with the input contact information, then this contact object is passed to hibernate, call session.save () to save. Hibernate will be responsible for generating and executing insertion queries. When the contact is inserted, the value of the ID field in the Contact class will be the same as the latest record primary key value in the Contact table. Hibernate will throw an exception if there is any problem. Please confirm that the copy JDBC drive JAR file is copied into the web-inf / lib directory, otherwise an exception will appear.

To try this example, download the sample1.zip file.

With the WebSphere Application Server connection pool to use Hibernate based on our content we have completed, we can improve the sample contact management application, which contains some key features of WebSphere Application Server.

First, when developing the above application, we use the connection pool in Hibernate. This connection pool algorithm is a bit unsatisfactory and cannot be used in the production environment, and you should consider using a third-party connecting pool such as Apache's DBCP. We will change our app to use the connection pool of WebSphere Application Server:

In order to use the WebSphere Application Server connection pool, you need to create a JDBC data source and set JNDI names, such as JDBC / DS1. (Refer to WebSphere Application Servers Information Center to see the details of the configuration data source.) In the hibernate.cfg.xml file, remove the hibernate.connection.driver_class, url, and other properties, and add this line: JDBC / DS1 In the AddContactAction.java execution method, we create a sessionFactory object each time, but this is not a good idea, because using sessionFactory Create thread security shared by all application threads. Objects are very expensive. We should only create a sessionFactory object when the application starts. We can create a sessionContextListener class and implement it by configuring sessionFactory, or create a Struts plug-in configured SESSIONFACTORY with a better way, as shown in Listing 3. Listing 3public class HibernateStrutsPlugIn implements PlugIn {public void init (ActionServlet arg0, ModuleConfig arg1) throws ServletException {try {SessionFactory sessionFactory = new Configuration () configure () buildSessionFactory ();..} Catch (HibernateException e) {System.out.println ("Error In Configuring SessionFactory); E.PrintStackTrace ();}} // Other methods} To create a structs plugin:

Create a HibernateStrutSplugin class that implements a PLUGIN interface. In this type of init () method, configure (). Configure (). BuildSessionFactory () method. Adding an entry for the new plug-in class in Struts-Config.xml, which can be implemented using Application Developer (Figure 2), or by manually editing struts-config.xml and adding the line in Listing 4 at the end. Figure 2. Struts Configuration File Editor Listing 4

HibernateSessionFactory We will update our app and add two new tables: Phone and Address. Also we must change AddContact.jsp to add these two new inputs. We want the application to complete the function that if the user specifies the phone number or address, a new record will be added to the appropriate table. In addition, all of this should be part of a transaction, that is, after adding contacts and phone numbers, the adding address suddenly has an error, then all related activities with this transaction should roll back, and will The user displays the wrong page. Create Address.java and Phone.java to describe Address and Phone tables and map through address.hbm.xml and contact.hbm.xml. Add elements to this two files in hibernate.cfg.xml. Listing 5

try {Context ctx = new InitialContext (); Object obj = ctx.lookup ( "HibernateSessionFactory"); sessionFactory = (SessionFactory) obj;} catch (NamingException e) {e.printStackTrace ();} session = sessionFactory.openSession () ; Transaction contactInsertTransaction = try {session.beginTransaction (); // Create new instance of Contact and set values ​​in it by reading them from form object Contact contact = new Contact (); // Prepare contact object session.save (contact); // check if value for phone is not null if Yes kil = (string) Contactform.get ("Phone"); if (Phonestr.Length ()! = 0) {// Code for Inserting New New New New New New New New phone here} // If you uncomment this line you will find out contact gets inserted // even if there is some problem afterwards / / * if (true) throw new RuntimeException ( "Test transaction exception"); * / // Code for Inserting new address contactinserttransaction.commit ();} catch (hibernateException e) {ContactInsertTransaction.roll Back (); return mapping.findforward ("failure");} finally {session.flush (); session.close ();} Due to these changes, we have:

Change the implementation method, get the sessionFactory reference from JNDI. Change the execution method, enabling the insertion of the contact, phone and address, runs in the transaction in Hibernate it managed.

If all things are working properly, we will submit transactions before closing the session. If you have any problems, we will call the Rollback () method in the transaction object.

Using WebSphere Application Server Transaction Management Use Hibernate second, we now want to change our app to make non-web clients can also access. In order to achieve this goal, we will create a stateless session bean, and publicly open an ADDContact () method, and move all business logic from the AddContactAction class into the ContactBean.java.

Because of the movement to the stateless session bean, we must initialize the method of hibernate. For binding objects, once JNDI is available, you should initialize Hibernate, and you should bind the SessionFactory object to JNDI. When the application server has completed the startup, WebSphere Application Server will allow us to register the rollback notification. Create a Java project called SampleListener in Application Developer, and in this project, create HibernateJndilistener.java, as shown in Listing 6. Listing 6

public class HibernateJNDIListener implements CustomService, NotificationListener {public void initialize (Properties arg0) throws Exception {NotificationFilterSupport filter = new NotificationFilterSupport (); filter.enableType (NotificationConstants.TYPE_J2EE _STATE_RUNNING); ObjectName target = new ObjectName ( "WebSphere: *, type = Server "); AdminServiceFactory.getAdminService () addNotificationListenerExtended (target, this, filter, null);.} public void handleNotification (Notification arg0, Object arg1) {try {TestConfiguration.init (); System.out.println (" Hibernate configured sucessfully ");} catch (hibernateException e) {E.PrintStackTrace ();}}} This class implements a CustomService interface using the management console in WebSphere Application Server. Figure 3. WebSphere Administration Console When the application server or node is started, this class will also start, and the control will be obtained in the initialize () method, which will register a hibernatejndilistner instance to receive type_j2ee_state_running notifications. The HibernateJndilistner class implements NOTIFICATIONListener to indicate that it is now available. When the binding object can use JNDI in WebSphere Application Server, it will call the NOTIFICATION () processing method in HibernateJndilistener. In this method, we will initialize SessionFactory and bind them in JNDI. If you want to work properly, all Hibernate maps and .hbm.xml files need to be at the same level with SampleListener.jar. Create a new Java project, Sampledb, and move the com.sample.db java file to this project, .hbm.xml and hibernate.cfg.xml files are also processed. Copy SampleDb.jar and SampleListener.jar to AppServer / lib, the following files are also processed:

Hibernate2.jar Do Dom4j.jar cgilib-ful-2.0.1.jar XML-Apis.jar Commons-Collection-2.1.jar ECACHE-0.7.jar. Start WebSphere Application Server, and check systemout.log, find the Hibernate configuration successfully Message. Now, we will use WebSphere Application Server transaction management to change our app, so that we add contact information will become part of an existing transaction. For example, after inserting new contact information, we may want to send a confirmation letter to the user. If we already have a message-driven bean to send E-mail, this additional information should be part of a transaction. We can combine with WebSphere Application Server transaction management by adding this entry in hibernate.cfg.xml. Net.sf.hibernate.Transaction.WebsphereTransActionManagerLookup In this example, we will not manually specify the boundary of the transaction. WebSphere Application Server will start a new transaction when it calls the AddContact () method. If the method has completed the execution operation, it does not throw any errors. At this time, the transaction will be submitted, otherwise it will roll back.

End the words When you use Hibernate, if you don't apply the server, you should use a complete architecture; for example, you have a Swing application to interact with the database. In this case Hibernate saves you a lot of low-level consumption. However, if you run the middleware, you can use the data source configured in WebSphere Application Server because it optimizes performance and you can share the same connection pool in multiple applications of the subordinate.

For enterprise applications, you may have a database, message system, and a variety of EIS systems, and you want all required systems to run in a transaction. In this case, you should use the Java Transaction API (JTA) provided by WebSphere Application Server in Hibernate; when Hibernate is managed, it implements this by delegate the call to the underlying database, but when it is cross-system There will be problems when it is not a database.

Reference

You can see this article in our website on our world. Use Struts to build open-source MVC application using WebSphere Studio V5 to write simple struts application Struts User's Guide Modifying an Application to use DynaActionForm use Hibernate your Java object persistence to IBM DB2 Universal Database no container object-relational mapping WebSphere Retail book

download

Name

Size

Download Method

Sample1.zip

5.0 MB

FTP | HTTP

Sample2.zip

5.0 MB

FTP | HTTP

Sample3.zip

5.6 MB

FTP | HTTP

About the author SUNIL Patil is a software engineer in the Lotus department of IBM India. He has four years of J2EE experience.

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

New Post(0)