Pages

Using Spring and Hibernate with WebSphere Application Server

Summary: If you’re considering using Spring or Hibernate with IBM® WebSphere® Application Server, this article explains how to configure these frameworks for various scenarios with WebSphere Application Server. This article is not an exhaustive review of either framework, but a critical reference to help you successfully implement such scenarios. (Updated with new security information.) This content is part of the IBM

Introduction

The Spring Framework, commonly referred to as Spring, is an open source project that aims to make the J2EE™ environment more accessible. Spring provides a framework for simple Java™ objects that enables them to make use of the J2EE container via wrapper classes and XML configuration. Spring’s objective is to deliver significant benefits to projects by increasing development productivity and runtime performance, while also improving test coverage and application quality.

Hibernate is an open source persistence and query framework that provides object-relational mapping of POJOs (Plain Old Java Objects) to relational database tables, as well as data query and retrieval capabilities.

While many organisations are interested in discovering what benefits they can obtain from using these frameworks, IBM wants customers who do use them to know that they can do so with WebSphere Application Server in a robust and reliable way. This article describes how these frameworks can be used with WebSphere Application Server, and explains best practices for a variety of use cases so that you can get started with Spring or Hibernate as quickly as possible.



Using Spring

Spring is generally described as a lightweight container environment, though it is probably 

more proper to describe it as a framework for simplifying development. The Spring Framework was developed by Interface21, based on publications by Rod Johnson on the dependency injection design pattern. Spring can be used either in standalone applications or with application servers. Its main concept is the use of dependency injection and aspect-oriented programming to simplify and smooth the transitions from development to testing to production.

One of the most often used scenarios involving Spring is to configure and drive business logic using simple Java bean classes. The Spring documentation should provide enough information to build an application using Spring beans; there is nothing WebSphere-specific about this. The following sections describe some of the usage scenarios for using Spring on WebSphere Application Server. Spring applications that are developed following the advice in this article should execute within a WebSphere Application Server or WebSphere Application Server Network Deployment environment with no difficulties.

Except where explicitly stated, the information presented here pertains to Versions 6.0.2.x, 6.1.x, and 7.0.x of WebSphere Application Server on all platforms.

Presentation tier considerations

This section describes considerations relating to the use of Spring in the Web-based presentation tier.

* Web MVC frameworks

Spring’s Web MVC framework is an alternative to other frameworks that have been around for some time. Web MVC frameworks delivered, used, and supported directly by WebSphere Application Server include JavaServer Faces (JSF) and Struts. Spring documentation describes how to integrate Spring with these Web frameworks. Use of any of these MVC is supported by WebSphere Application Server, although IBM will only provide product support for the frameworks shipped with WebSphere Application Server.
* Portlet MVC framework

Spring also provides a Portlet MVC framework (which mirrors the Spring Web MVC framework) and runs in both the WebSphere Portal V6.0 and the WebSphere Application Server V6.1 portlet containers. (See Spring Portlet MVC for an example set of Spring portlets.) Running portlets in the WebSphere Application Server V6.1 portlet container requires that an additional Web application be created to define the layout and aggregation of the portlets. Information on how to use the portlet aggregator tag library can be found in the WebSphere Application Server Information Center and in the article Introducing the portlet container. Using JSF in combination with portlets is a common practice for rendering. For information on how Spring, Hibernate, JSF, and WebSphere Portal can be combined together, see Configuring Hibernate, Spring, Portlets, and OpenInSessionViewFilter with IBM WebSphere Portal.

Data access considerations

This section describes considerations relating to the configuration of Spring beans that access data within a transaction.

The Spring framework essentially wraps Spring beans with a container-management layer that, in a J2EE environment, delegates to the underlying J2EE runtime. Following are descriptions of how Spring beans should be configured so that the Spring Framework properly delegates to (and integrates with) the WebSphere Application Server runtime.

* Accessing data sources configured in WebSphere Application Server

WebSphere Application Server manages the resources used within the application server execution environment. Spring applications that want to access resources, such as JDBC data sources, should utilize WebSphere-managed resources. To do this:
1. During development, the WAR module should be configured with a resource reference. For example:


jdbc/springdb
javax.sql.DataSource
Container
Shareable

2. For EJB JAR files, the same resource-ref should be declared in each EJB that needs to access the data source.
3. A data source proxy bean would then be declared within the Spring application configuration, which references a WebSphere-managed resource provider:








Accessing the data source through this proxy bean will cause the data source to be looked up using the module’s configured references, and hence be properly managed by WebSphere Application Server. Note that the jndiName property value matches the pattern java:comp/env/ concatenated with the res-ref-name declared in the resource-ref.

Alternatively, from Spring 2.5 onwards, this can be done using the approach. Notice how the jndiName property matches the actual value of the res-ref name declared in the resource-ref together with the resource-ref=”true” property:



4. The data source proxy bean may then be used by the Spring application as appropriate.
5. When the application is deployed to a WebSphere Application Server, a resource provider and resource data source must be configured in the normal fashion for use by the Spring application resource reference. The resource reference declared within the module’s deployment descriptor will be bound to the application server’s configured data source during deployment.
* Using JDBC native connections

Spring provides a mechanism for accessing native connections when various JDBC operations require interacting with the native JDBC resource. The Spring JdbcTemplate classes utilize this capability when a NativeJdbcExtractor class has been set on the JdbcTemplate class. Once a NativeJdbcExtractor class has been set, Spring always drills down to the native JDBC connection when used with WebSphere Application Server. This bypasses the following WebSphere quality of service functionality and benefits:
o Connection handle tracking and reassociation
o Connection sharing
o Involvement in transactions
o Connection pool management.

Another problem with this is the WebSphereNativeJdbcExtractor class depends on internal WebSphere adapter classes. These internal classes may differ by WebSphere Application Server version and may change in the future, thereby breaking applications that depend on this functionality.

Use of NativeJdbcExtractor class implementations (for example, WebSphereNativeJdbcExtractor) are not supported on WebSphere Application Server and you should avoid scenarios that require it. The alternative is to use the WebSphere Application Server WSCallHelper class to access non-standard vendor extensions for data sources.
* Using transactions with Spring

WebSphere Application Server provides a robust and scalable environment for transaction processing and for managing connections to resource providers. Connections to JDBC, JMS, and Java Connector resource adapters are managed by WebSphere Application Server regardless of whether or not a global transaction is being used; even in the absence of a global transaction there is always a runtime context within which all resource-provider connections are accessed. WebSphere Application Server refers to this runtime context as a local transaction containment (LTC) scope; there is always an LTC in the absence of a global transaction, and resource access is always managed by the runtime in the presence of either of a global transaction or an LTC. To ensure the integrity of transaction context management (and hence the proper management of transactional resources) WebSphere Application Server does not expose the javax.transaction.TransactionManager interface to applications or application frameworks deployed into WebSphere Application Server.

There are a number of ways to drive resource updates under transactional control in Spring, including both programmatic and declarative forms. The declarative forms have both Java annotation and XML descriptor forms. If you use Spring 2.5 with WebSphere Application Server V6.0.2.19 or V6.1.0.9 or later, you can take advantage of full support for Spring’s declarative transaction model. Spring 2.5 has a new PlatformTransactionManager class for WebSphere Application Server, called WebSphereUowTransactionManager, which takes advantage of WebSphere Application Server’s supported UOWManager interface for transaction context management. Managing transaction demarcation through WebSphere Application Server’s UOWManager class ensures that an appropriate global transaction or LTC context is always available when accessing a resource provider. However, earlier versions of Spring used internal WebSphere interfaces that compromised the ability of the Web and EJB containers to manage resources and are unsupported for application use. This could leave the container in an unknown state, possibly causing data corruption.

Declarative transaction demarcation in Spring 2.5 or later are supported in WebSphere Application Server using the following declaration for the WebSphere transaction support:



A Spring bean referencing this declaration would then use standard Spring dependency injection to use the transaction support, for example:





...



PROPAGATION_REQUIRED



Alternatively, from Spring 2.5 onwards, Spring’s AspectJ support can be utilised. In the following example, can be applied to various parts of the application. This indicates that all methods starting with “get” are PROPAGATION_REQUIRED and all methods starting with “set” are PROPAGATION_REQUIRES_NEW. All other methods use the default transaction settings.









The tag applies those settings to any executed operation defined within the class MyService.






Another alternative mechanism for declaring transaction settings is to use the Spring annotation-based transaction support. This requires the use of Java 5+, and therefore cannot be used with WebSphere Application Server V6.0.2.x.

Add the following to the Spring.xml configuration:



Any methods that require transactional attributes should then be marked with the @Transactional annotation:

@Transactional(readOnly = true)
public String getUserName()
{ ...

Be aware that the @Transactional annotation can only be used to annotate public methods.

The WebSphereUowTransactionManager supports each of the Spring transaction attributes:
o PROPAGATION_REQUIRED
o PROPAGATION_SUPPORTS
o PROPAGATION_MANDATORY
o PROPAGATION_REQUIRES_NEW
o PROPAGATION_NOT_SUPPORTED
o PROPAGATION_NEVER

For earlier versions of Spring that do not provide org.springframework.transaction.jta.WebSphereUowTransactionManager, and for versions of WebSphere Application Server prior to V6.0.2.19 or V6.1.0.9 that do not provide com.ibm.wsspi.uow.UOWManager, transaction support in WebSphere Application Server is available via this Spring configuration:





This configuration supports a restricted set of transaction attributes that does not include PROPAGATION_NOT_SUPPORTED and PROPAGATION_REQUIRES_NEW. The Spring class org.springframework.transaction.jta.WebSphereTransactionManagerFactoryBean, which also claims to provide PROPAGATION_NOT_SUPPORTED and PROPAGATION_REQUIRES_NEW capabilities, uses unsupported internal WebSphere Application Server interfaces and should not be used with WebSphere Application Server.
* Using Spring JMS

Just as with accessing JDBC data sources, Spring applications intended to access JMS destinations must ensure they use WebSphere-managed JMS resource providers. The same pattern of using a Spring JndiObjectFactoryBean as a proxy for a ConnectionFactory will ensure that JMS resources are properly managed.

For JMS message sending or synchronous JMS message receipt, JMSTemplates can be used. This includes the use of Spring’s dynamic destination resolution functionality both via JNDI and true dynamic resolution.

The following example shows the configuration of a resource reference for a ConnectionFactory. This reference is mapped during application deployment to point to a configured, managed ConnectionFactory stored in the application server’s JNDI namespace. The ConnectionFactory is required to perform messaging and should be injected into the Spring JMSTemplate.


jms/myCF
javax.jms.ConnectionFactory
Container
Shareable


There is now a defined JNDI name for your ConnectionFactory within the application that can be looked up and injected into the JMSTemplate:










...








At run time, the JMSTemplate can locate destinations based on either their JNDI name (as configured in an application resource reference) or through “dynamic resolution,” based on the administrative name of the destination configured in WebSphere Application Server; for example, for the JMS myQueue queue, bound to a JNDI reference of jms/myQueue:

JNDI resolution:
jmsTemplate.send("java:comp/env/jms/myQueue", messageCreator);

Dynamic resolution:
jmsTemplate.send("myQueue", messageCreator);

As an alternative to J2EE message-driven beans (MDBs), Spring provides a message-driven POJO model for processing inbound JMS messages asynchronously. Only a DefaultMessageListenerContainer class will manage messages from the JMS queue to the configured POJO that must be a javax.jms.MessageListener implementation.

In a WebSphere Application Server environment, you must also specify a WorkManagerTaskExecutor class, which means the DefaultMessageListenerContainer class will delegate to a server-managed thread pool. The DefaultMessageListenerContainer should also be configured with the server’s transaction management via the WebSphereUowTransactionManager, as described above.





















While this message-driven POJO model can be used, it is recommended that J2EE message-driven beans (MDBs) be used directly in WebSphere Application Server configurations that require workload management and/or high availability. Be aware that no other Spring JMS MessageListenerContainer types are supported, as they can start unmanaged threads and might also use JMS APIs that should not be called by applications in a Java EE environment.
* Using JPA with Spring

The EJB 3.0 specification defines the Java Persistence API (JPA) as the means for providing portable persistent Java entities. WebSphere Application Server V7 and the WebSphere Application Server V6.1 EJB 3 feature pack both provide implementations of EJB 3 and JPA; it is also possible to use the Apache OpenJPA implementation of JPA with WebSphere Application Server V6.1 (see Resources). When Spring is used in conjunction with a JPA implementation, you should use JPA directly rather than using Spring’s JPA helper classes (in the org.springframework.orm.jpa package).

WebSphere Application Server V6.1 and later supports JPA application-managed entity managers, which might have a transaction type of either JTA or resource-local. JTA entity manager uses the application server’s underlying JTA transaction support, for which transaction demarcation can be defined using either standard J2EE techniques or Spring’s declarative transaction model, as described above.

A data access object (DAO) that uses JPA is packaged with a persistence.xml that defines persistence context for the JPA EntityManager used by the application. For example, a persistence.xml for a JTA entity manager that uses the data source with a JNDI name “java:comp/env/jdbc/springdb” can be set up like this:



org.apache.openjpa.persistence.PersistenceProviderImpl
java:comp/env/jdbc/springdb








By setting the openjpa.TransactionMode and openjpa.ConnectionFactoryMode properties to “managed,” the JPA entity manager delegates management of transactions and connections to WebSphere Application Server. The DAO may use Spring’s declarative transaction demarcation as described above.

Annotation style injection of a JPA EntityManager is also possible. This is identical to standard JPA:

@PersistenceContext
private EntityManager em;

You need this XML code to turn on EntityManager injection in the Spring XML configuration:




Spring will create an EntityManager from any EntityManagerFactory defined in this XML file. If more than one exists, then it will fail. Use one (and only one) of these ways to create an EntityManagerFactory:
o Using Spring’s basic configuration





o Using Spring’s advanced configuration







Of course, the benefits of annotations and JPA are also available by using the pure EJB 3 support in WebSphere Application Server V7 and the WebSphere Application Server V6.1 EJB 3 Feature Pack. In either case, you can create an EntityManagerFactory using the JPA API, as shown below. This approach is not recommended for a non-EJB 3 environment, because any EntityManagers created might not be properly managed. However, when you do have an EJB 3 environment, you can use this approach to separate your Spring and JPA configurations.


* Spring EntityManagerFactory and JPA When using JPA, there is a conflict in the Spring EntityManagerFactory that requires configuring the entityManagerFactoryInterface property. This issue and its resolution are documented on the Spring Web site. * IBM JDK 6 WebSphere Application Server V7 runs on IBM JDK 6, which cannot be used with versions of the Spring framework prior to V2.5.5, due to a Spring problem documented within this JIRA. Spring security considerations Spring provides a security framework that differs significantly from the standard Java EE security framework. In some cases, this framework can rely on the underlying Java EE security runtime, and in other cases, the Spring security framework completely replaces it. The Spring implementation of an authentication provider enables integration with the container, but only at the level of calling a specific subroutine, org.springframework.web.filter.DelegatingFilterProxy, which is implemented as a servlet filter and configured in web.xml for the url pattern /* so that it gets called on every request. In terms of applicability to WebSphere Application Server authentication, see this article on the WebSphere Application Server authentication process and various options for extending or customizing WebSphere Application Server authentication before you proceed with any of the three common use patterns listed below — or any other implementation using org.springframework.web.filter.DelegatingFilterProxy: * The servlet filter is employed to replace J2EE container security. In this case, WebSphere Application Server J2EE security is not used. Either security is not enabled, or, if it is employed, no J2EE authorization constraint is defined in the web.xml. Spring security has its own security context (stored in the HTTP session for a user, by default) and uses GrantedAuthority objects to determine a user’s permissions on resources. The Spring security context is used for all authorization decisions. Since there is no Java EE security context, none of the WebSphere Application Server security features (such as, authorization, SSO integration with proxies, Java EE application SSO, SPNEGO integration, identity propagation to EJBs, services, databases, and so on) apply. * The servlet filter is used in conjunction with a Spring “pre-authenticated authentication provider,” which is conceptually similar to a WebSphere Application Server Trust Association (TAI). Here, J2EE security is enabled and there is a J2EE authorization constraint in the web.xml, so normal container authentication takes place. The pre-authenticated authentication provider extracts the username from the runtime and then calls isUserInRole() on a set of predefined roles. These roles are mapped to GrantedAuthority objects, and from then on the Spring security context is used. In this case, there is a valid Java EE security context and WebSphere Application Server security features are available — with the caveat that Spring-specific security features might or might not honor WebSphere Application Server security behavior. One such example is that it is possible to change the identity on a thread using WebSphere Application Server APIs, but that behavior may or may not be consistent when Spring security is employed. * The servlet filter is used in conjunction with a Spring JAAS authentication provider. As with the first case listed, WebSphere Application Server J2EE security is likely not even enabled, or, if it is, there is no J2EE authorization constraint defined in the web.xml. However, the actual task of authenticating the credentials obtained by the filter is delegated to the container by use of what is (from the WebSphere Application Server point of view) an application JAAS login. The login module and login configuration used are specific to the container in use, and Spring callback handlers are supplied to provide the username and password of the user. When the login is complete, the principals are obtained from the subject using loginContext().getSubject().getPrincipals(), and they are passed to a piece of code called an AuthorityGranter, which decides what GrantedAuthority objects to grant based on the Principal objects; be aware that the GrantedAuthority objects are not based on J2EE roles here. From here on, the Spring security context is used. However, from a WebSphere Application Server security perspective, the ltpaLoginModule is only a small part of the security runtime and this module is not designed to be called in isolation; rather, it is designed to be called as part of a login configuration to instantiate a JAAS subject. The actual instantiation of the JAAS subject is done by a second module, com.ibm.ws.security.server.lm.wsMapDefaultInboundLoginModule. It is only after this second login module is called that a WebSphere Application Server security context is created. As a result, because the WebSphere Application Server login module in question is not intended to be used this way, using it directly in the manner described has unpredictable consequences. Moreover, users implementing this approach have encountered serious performance issues, in addition to suffering from the same limitations mentioned in the first pattern. Of these, only the second use case listed above can be considered true “integration” because J2EE security is used for authentication and the Spring security context is used for subsequent authorization — although since the Spring security context is stored by default in the HTTP session (which is a security anti-pattern because HTTP session is not secure), you should steer clear of the default. If you choose to employ this pattern, you must to go to extra lengths to protect the session — which is not normally considered to be part of the security infrastructure; for example, you’ll need to protect the session cookie and should enable WebSphere Application Server session security integration. (See WebSphere Application Server V7 advanced security hardening for more.) Rather than storing Spring security context in an HTTP session, a better option would be to extend Spring to store the context in the JAAS subject instead, which will require additional custom development. As mentioned elsewhere in this article, this guidance should not be considered to be exhaustive. The points presented here with respect to Spring security do not constitute a discussion of all possible implications of using Spring security; rather, it is simply a list of issues that users have encountered from the inappropriate use of Spring security. While it might be possible to extend Spring security to provide reasonably secure integration with WebSphere Application Server and other Java EE applications that do not use Spring, you should always leverage the security implementation provided by WebSphere Application Server for applications running in WebSphere Application Server. Not only will this ensure robust and reliable security integration, but the security that is provided will be fully supported within WebSphere Application Server. One feature of Spring security that users seem to like is the authorization framework, which goes beyond what native Java EE authorization provides. If this is your primary reason for considering Spring security, you should investigate other, less disruptive options, such as IBM Tivoli Security Policy Manager or writing your own custom authorization, perhaps using your own access control lists. Using HttpSessionContextIntegrationFilter and forceEagerSessionCreation You should always use WebSphere Application Server security mechanisms to secure your WebSphere Application Server applications. If you use the Spring Security filter HttpSessionContextIntegrationFilter, however, here is a problem scenario you should watch for. HttpSessionContextIntegrationFilter executes after the call to the WebSphere Application Server server-side application code has been made; for example, the filter runs after a call to index.jsp has been made, which returns response data. As a result, the response will already have been committed when the call to create a session is reached in the Spring filter, and so the HTTP headers have already been returned. Since a Set-Cookie header must be added to the HTTP response, and the response has already been sent, a Java EE compliant container (such as WebSphere Application Server) might throw an IllegalStateException causing the Set-Cookie to fail. It has been observed that this exception is suppressed in at least some versions of Spring Security, which might lead to a NullPointerException later on — making it very difficult to determine exactly what happened. To avoid this problem, you can set the forceEagerSessionCreation option on the HttpSessionContextIntegrationFilter entry to true in your Spring configuration: Integration and management considerations * JMX and MBeans Spring JMX MBeans are supported on WebSphere Application Server V6.1 and later only when registered with WebSphere Application Server’s container manager MBeanServer. If no server property is specified, the MBeanExporter tries to automatically detect a running MBeanServer. When running an application in WebSphere Application Server, the Spring framework will therefore locate the container’s MBeanServer. You should not use MBeanServerFactory to instantiate an MBeanServer and then inject it into the MBeanExporter. Furthermore, the use of Spring’s ConnectorServerFactoryMBean or JMXConnectorServer to expose the local MBeanServer to clients by opening inbound JMX ports is not supported with WebSphere Application Server. Spring JMX MBeans are not supported on WebSphere Application Server prior to Version 6.1. * Registering Spring MBeans in WebSphere Application Server WebSphere Application Server MBeans are identified by a javax.management.ObjectName when they are registered that looks like this: WebSphere:cell=99T73GDNode01Cell,name=JmxTestBean,node=99T73GDNode01, process=server1,type=JmxTestBeanImpl This means that when they are de-registered, they need to be looked up with the same “fully qualified” name, rather than the simple name property of MBean. The best approach is to implement org.springframework.jmx.export.naming.ObjectNamingStrategy, which is an interface that encapsulates the creation of ObjectName instances and is used by the MBeanExporter to obtain ObjectNames when registering beans. An example is available on the Spring Framework forum. You can add the ObjectNamingStrategy instance to the bean that you register. This will ensure that the MBean is properly de-registered when the application is uninstalled. ... * MBeans ObjectNames and notifications Due to the use of a fully qualified ObjectName for MBeans in WebSphere Application Server, you are advised to fully define that ObjectName to use notifications. This JIRA enables the Spring bean name to be used instead and should provide a fix, but only if you are on the appropriate version of Spring. * System z multicall/unicall limitation As Spring doesn’t allow the specification of platform-specific fields in the MBean descriptor, Spring JMX will work on multi-SR servers on WebSphere Application Server V6.1, but you are restricted in your deployment options. WebSphere Application Server will default to the unicall strategy so that only one instance of the MBean (in one, indeterminate SR) will be asked to execute a request. This may be sufficient in some scenarios but it is more likely that an application will require the ability to declare a combination of multicall and unicall methods, and possibly result in aggregation logic. * Scheduling and thread pooling Spring provides a number of TaskExecutor classes that can be used for scheduling work. The only Spring TaskExecutor that is supported by WebSphere Application Server for executing work asynchronously is the Spring WorkManagerTaskExecutor class, which properly utilizes thread pools managed by WebSphere Application Server and delegates to a configured WorkManager. Other TaskExecutor implementations might start unmanaged threads. You can setup a WorkManager within the WebSphere Application Server administrative console by navigating to Resources => Asynchronous beans => Work managers . The JNDI name for the resource can then be used in the Spring config file as a workManagerName property to define a WorkManagerTaskExecutor. This example uses WebSphere Application Server’s DefaultWorkManager JNDI name or wm/default: * Classloaders Spring and WebSphere Application Server both use several open source projects and, unfortunately, the versions of the projects they have in common won’t always match. Spring dependencies should be packaged as part of the application, and the server should be setup as described below to avoid conflicts. Otherwise, the classloaders may not load the appropriate version either for the runtime or for the application. Usually, this will cause exceptions to appear in the log regarding version mismatches of classes, ClassCastExceptions, or java.lang.VerifyErrors. One example is the use of Jakarta Commons Logging. Configuring Jakarta Commons Logging (JCL) for application use, or utilizing a different version of JCL than is provided by the application server (for example, embedded with the application code) requires specialized configuration on WebSphere Application Server. See Integrating Jakarta Commons Logging for strategies on how to configure a deployed application to use an embedded version of commonly used technologies. Keep an eye on the support Web site for updates on how to configure embedded JCL on WebSphere Application Server V6.x products. This is just one example of conflicts. Others might include application use of JDOM or specific versions of JavaMail. Replacement of WebSphere Application Server’s JAR files with these or other packages with later or different versions is not supported. Another classloader problem that may plague Spring users on WebSphere Application Server is the way Spring loads resources. Resources can include things such as message bundles, and with the classloader hierarchy and various policies for locating resources within the hierarchy, it is possible for resources using a common name to be found in an unintended location. The WebSphere Application Server classloader viewer can be used to help resolve this problem. The combination of this and other versions of common libraries may require that the application rename resources to a unique name. The example explained by James Estes on the Spring forum contains an EJB project and a Web project packaged into an EAR file. The solution described is to add the spring.jar file into both the WEB-INF/lib and the top level of the EAR, then set the classloader policy for the WEB project to PARENT LAST so that it finds the version in WEB-INF/lib first. The EJB project uses the version in the EAR. Design considerations Some of the infrastructure services provided by the Spring Framework replicate services provided by a standards-based application server runtime. Furthermore, the abstraction of the Spring framework infrastructure from the underlying J2EE application server necessarily weakens the integration with application server runtime qualities of service, such as security, workload management, and high availability. As a result, using the Spring Framework in applications deployed into the WebSphere Application Server must be carefully considered during application design to avoid negating any of the qualities of service provided by WebSphere Application Server. Where no other recommendation is made, directly using the services provided by WebSphere Application Server is preferred in order to develop applications based on open standards and ensure future flexibility in deployment. * Unmanaged threads There are some Spring scenarios that can lead to unmanaged thread creation. Unmanaged threads are unknown to WebSphere Application Server and do not have access to Java EE contextual information. In addition, they can use resources without WebSphere Application Server knowing about it, exist without an administrator’s ability to control their number and resource usage, and impede on the application server’s ability to gracefully shutdown or recover resources from failure. Applications should avoid any scenario that causes unmanaged threads to be started, such as: o registerShutdownHook Avoid using the Spring AbstractApplicationContext or one of its subclasses. There is a public method, registerShutdownHook, that creates a thread and registers it with the Java VM to run on shutdown to close the ApplicationContext. Applications can avoid this by utilizing the normal lifecycle notices they receive from the WebSphere container to explicitly call close on the ApplicationContext. o WeakReferenceMonitor Spring provides convenience classes for simplified development of EJB components, but be aware that these convenience classes spawn off an unmanaged thread, used by the WeakReferenceMonitor, for cleanup purposes. * Scheduling Spring provides (or integrates with) a number of scheduling packages, but the only Spring scheduling package that works with threads managed by WebSphere Application Server is the CommonJ WorkManager. Other packages, such as quartz and the JDK Timer, start unmanaged threads and should be avoided. Back to top Using Hibernate Hibernate is an open source persistence framework for POJOs, providing object-relational mapping of POJOs to relational database tables using XML configuration files. The Hibernate framework is a data access abstraction layer that is called by your application for data persistence. Additionally, Hibernate provides for the mapping from Java classes to database tables (and from Java data types to SQL data types), as well as data query and retrieval capabilities. Hibernate generates the requisite SQL calls and also takes care of result set handling and object conversion. Hibernate, like OpenJPA, implements the Java Persistence APIs (JPA) specification, which is a mandatory part of Java EE 5. (See Resources for developerWorks articles on using Hibernate.) Usage scenarios The following scenarios describe some of the possible scenarios for how to use Hibernate with WebSphere Application Server and WebSphere stack products. These are only example scenarios and should not be considered recommended scenarios. * Use a WebSphere Application Server data source In order for Hibernate to get database connections from WebSphere Application Server, it must use a resource reference, as mandated by the Java EE (formerly known as J2EE) specification. This ensures WebSphere Application Server can provide the correct behavior for connection pooling, transaction semantics, and isolation levels. Hibernate is configured to retrieve a data source from WebSphere Application Server by setting the hibernate.connection.datasource property (defined in the Hibernate configuration file) to refer to a resource reference (for example, java:comp/env/jdbc/myDSRef) defined in the module’s deployment descriptor. For example: java:/comp/env/jdbc/myDSRef Java EE resource references for Web applications are defined at the WAR file level, which means all servlets and Java classes within the container share the resource reference. Inside of an EJB module, resource references are defined on the individual EJB components. This means that, if many EJB components use the same Hibernate configuration, each EJB must define the same reference name on each EJB component. This can lead to complications that will be discussed a bit later. Once a data source is configured, one of the next steps to ensure that Hibernate works correctly is to properly configure transaction support. * Transaction strategy configuration Hibernate requires the configuration of two essential pieces in order to properly run with transactions. The first, hibernate.transaction.factory_class, defines transactional control and the second, hibernate.transaction.manager_lookup_class, defines the mechanism for registration of transaction synchronization so the persistence manager is notified at transaction end when it needs to synchronize changes with the database. For transactional control, both container-managed and bean-managed configurations are supported. The following properties must be set in Hibernate.cfg.xml when using Hibernate with WebSphere Application Server: o for container-managed transactions: org.hibernate.transaction.CMTTransactionFactory org.hibernate.transaction.WebSphereExtendedJTATransactionLookup o for bean-managed transactions: org.hibernate.transaction.JTATransactionFactory org.hibernate.transaction.WebSphereExtendedJTATransactionLookup java:comp/UserTransaction
The jta.UserTransaction property configures the factory class to obtain an instance of a UserTransaction object instance from the WebSphere container.

The hibernate.transaction.manager_lookup_class property is supported on the WebSphere platform by WebSphere Application Server V6.x and later, and on WebSphere Business Integration Server Foundation V5.1 and later. This property configures Hibernate to use the ExtendedJTATransaction interface, which was introduced in WebSphere Business Integration Server Foundation V5.1 and WebSphere Application Server V6.0. The WebSphere ExtendedJTATransaction interface establishes a pattern that is formalized in Java EE 5 via the JTA 1.1 specification.
* Unsupported transaction configurations

The Hibernate documentation describes transaction strategy configurations for running on WebSphere Application Server Versions 4 and 5 products; however, these configurations use internal WebSphere interfaces and are not supported on those earlier versions. The only supported transaction configuration of Hibernate is described above, which means, as stated earlier, Hibernate usage is only supported on WebSphere Business Integration Server Foundation V5.1 and on WebSphere Application Server Version 6.x and later.
* Hibernate’s usage patterns within a WebSphere Application Server environment

Hibernate’s session-per-request and long conversation patterns are both available when using Hibernate with WebSphere Application Server. Customers must choose which is appropriate for their application, though it is our opinion that session-per-request offers better scalability.
o Multiple isolation levels

Sharable connections provide a performance improvement in WebSphere Application Server by enabling multiple resource users to share existing connections. However, if sharable connections and multiple isolation levels are both necessary, then define a separate resource-ref and Hibernate session-factory for each connection configuration. It is not possible to change the isolation level of a shared connection. Therefore, it is also not possible to use the hibernate.connection.isolation property to set the isolation level on a sharable connection. See Sharing connections in WebSphere Application Server V5 for more information on policies and constraints on connection sharing. (Although this article generally pertains to all shared connection use on WebSphere Application Server V5, the connection sharing advice still follows for Hibernate running on V6.x.)
o Web applications

Hibernate long conversation sessions can be used and stored in HttpSession objects; however, a Hibernate session holds active instances and, therefore, storing it in an HttpSession may not be a scalable pattern since sessions may need to be serialized or replicated to additional cluster members. It is better to use HttpSession to store disconnected objects (as long as they are small, meaning 10KB to 50KB) and re-associate them with a new Hibernate session when an update is needed. This is because HttpSession is best used for bookmarking and not caching. A discussion on how to minimize memory use in HttpSession is contained in Improving HttpSession Performance with Smart Serialization. Instead of using HttpSession as a cache, consider using a WebSphere data caching technology like ObjectGrid or DistributedObjectCache, as described in the next section.

For best practices on high performing and scalable applications, the book Performance Analysis for Java Websites is strongly recommended.

At the time of publication, the behavior of Hibernate’s cluster aware caches in conjunction with WebSphere Application Server has not been determined; therefore, it is not yet determined whether or not their use is supported and we will not discuss them further. As a result, customers requiring a distributed cache should consider creating a class that implements org.hibernate.cache.CacheProvider using the property hibernate.cache.provider_class, which employs one of the two distributed cache implementations in WebSphere.

* Integrating a second-level cache

A Hibernate session represents a scoping for a unit of work. The Session interface manages persistence during the lifecycle of a Hibernate session. Generally, it does this by maintaining awareness or state of the mapped entity class instances it is responsible for by keeping a first-level cache of instances, valid for a single thread. The cache goes away when the unit of work (session) is completed. A second-level cache also can be configured to be shared among all sessions of the SessionFactory, including across a cluster. Be aware that caching in Hibernate raises issues that will need to be addressed. First, no effort is made to ensure the cache is consistent, either with external changes to the database or across a cluster (unless using a cluster aware cache). Second, other layers (such as the database) may already cache, minimizing the value of a Hibernate cache. These issues must be carefully considered in the application design, but they are beyond the scope of this article.

Hibernate comes with several pre-configured caches. You can find information on them in the Hibernate Cache documentation pages. For read-only data, one of the in-memory caches might be enough. However, when the application is clustered and a cluster aware cache is needed, the local read-only caches are not enough. If a distributed cache is desired, we recommend using one of the WebSphere-provided distributed cache implementations. These can be used as a second level cache with Hibernate:
o The DistributedMap/DistributedObjectCache interfaces provide distributed cache support the WebSphere v6.x product family. See Using the DistributedMap and DistributedObjectCache interfaces for the dynamic cache for more information.
o ObjectGrid, available as part of the WebSphere Extended Deployment product, provides extensible object caching support. See ObjectGrid for more information.
* Using Hibernate in WebSphere Enterprise Service Bus and WebSphere Process Server

WebSphere Process Server and WebSphere Enterprise Service Bus (ESB) rely on the Service Component Architecture (SCA) and Service Data Objects (SDO) as an assembly and programming model for SOA. (See Resources to learn more about SCA and SDO.) SCA components are not Java EE components, so they do not have resource references, but rely instead on services and adapters to connect to systems. Resource references cannot be used when building Java SCA components; therefore, Hibernate cannot be used directly by an SCA component.

In this case, Hibernate persistence should be hidden behind some kind of facade. There are two alternatives:
o A local EJB session facade is created to wrap Hibernate persistence. The session facade provides adapter logic to map Hibernate entity POJOs to Service Data Objects and back. An integration developer can then use an EJB import to invoke the session facade, and invoke it in a tightly coupled fashion with corresponding Qualities of Service (QoS).
o An EJB Web service session facade is created to wrap Hibernate persistence. An integration developer can then use a Web service import to invoke the Web service for persistence. This gets around having to build POJO to SDO converters, since at the current time SCA only uses SDO for data types. Figure 1 illustrates a business process using both patterns, though the details of the process are beyond the scope of this article.

Figure 1. Sample business process
Figure 1. Sample business process
* Hibernate JPA API on WebSphere Application Server V6.1

Hibernate’s JPA support provides for JPA standard persistence and is a good alternative to the proprietary Hibernate APIs. Hibernate’s JPA implementation requires a Java SE 5 based runtime, and therefore only runs on WebSphere Application Server V6.1 or later. At the time of publication, Hibernate’s JPA support does not run on WebSphere System z or iSeries platforms. The Hibernate documentation describes how to package and deploy applications using Hibernate’s JPA implementation.
* Non-interoperable / Non-portable function

Section 3.2.4.2 in the JPA specification describes a scenario that is likely to cause interoperability and potential portability problems. This has to do with the combination of the use of lazy loading (that is, @Basic(fetch=LAZY)) and detached objects. When merging a detached object back into a session, JPA will examine the object and update the data store with any changed values. However, data objects are simple POJOs. If part of the POJO state wasn’t loaded when it was detached, it can appear to be changed when it is merged back in. To get this to work correctly, vendors must implement serialization techniques specific to their runtime. This is not interoperable and the semantics may not be portable either.

Back to top

Product and customer technical support

An area of reasonable concern for users is support of projects using open source and the impact of that usage upon a vendor’s support for its licensed products. IBM recognizes that some customers may desire to use non-IBM frameworks in conjunction with IBM WebSphere Application Server and is providing information to customers that may promote the creation of the most reliable operating environment for IBM WebSphere Application Server. IBM considers open source code and application frameworks installed by customers, either bundled as part of the application or as shared libraries, to be part of application code. By carefully utilizing this information when using open source projects, customers may use IBM products with a higher degree of confidence that they may have continued access to IBM product and technical support. If a problem is encountered when using these frameworks with WebSphere products, IBM will make reasonable efforts to ensure the problem does not lie with the WebSphere product.

It is expected that customers may safely use frameworks such as Spring and Hibernate on IBM products by observing the suggestions of this article and understanding a few key points:

* Customers must ensure that they only use those frameworks in ways that are allowed by WebSphere Application Server. In particular, this means that frameworks should not be used when they use internal product interfaces — unfortunately many open source frameworks do this when not configured carefully. Customers should avoid scenarios clearly documented as things to avoid on WebSphere.
* For open source frameworks, customers should ensure they understand and have access to matching source code and binaries for the framework they are using with WebSphere Application Server.
* Customers are encouraged to obtain corrective service for the frameworks from the open source community or from partners working with the open source community.

For more details on IBM support and policy please refer to the IBM Support Handbook and WebSphere Application Server Support Statement.

Although following the suggested practices of this article will help you enhance your experience when using WebSphere Application Servers in an open source environment, it is not an all inclusive list of ways in which an open source component may impact WebSphere Application Server operation or the operation of other components. Users of open source code are urged to review the specifications of all components to avoid licensing, support, and technical issues.

Throughout this article, the terms “support” or “supported” indicates that the usage being described uses only IBM documented functionality. The authors have done their best to provide advice on how to configure and use these frameworks to ensure that their usage is consistent with documented product behavior, but this article is neither an endorsement nor a statement of support for Spring or Hibernate.

More Here


Courtesy:http://skysoftarchive.wordpress.com/2010/11/21/using-spring-and-hibernate-with-websphere-application-server/

8 comments:

  1. Are you trying to earn money from your websites with popup ads?
    In case you are, have you ever considered using PopCash?

    ReplyDelete
  2. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    Devops Training courses
    python Training in chennai
    Devops Training in Bangalore

    ReplyDelete
  3. This is quite educational arrange. It has famous breeding about what I rarity to vouch.
    Colossal proverb. This trumpet is a famous tone to nab to troths. Congratulations on a career well achieved.
    This arrange is synchronous s informative impolite festivity to pity. I appreciated what you ok extremely here.


    Selenium interview questions and answers
    Selenium Online training
    Selenium training in Pune
    selenium training in USA
    selenium training in chennai

    ReplyDelete
  4. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.
    oracle training in chennai

    oracle training in omr

    oracle dba training in chennai

    oracle dba training in omr

    ccna training in chennai

    ccna training in omr

    seo training in chennai

    seo training in omr

    ReplyDelete