Friday 25 September 2009

I must say, I am not very convinced to use EXTENDED PERSISTENCE CONTEXT

Introduction

I decided to share a special situation that I lived when I attempted to improve my code following some JEE specification principles. But as always, the thing is not easy. I realised that the two possible solutions did not work because of hibernate bug. Therefore I had to adapt my solution with a hibernate workaround.

Initial situation

We have the screen that shows:


§          Entity A instance name property.
§          Description properties from B instances linked with A instance.
§          Description properties from C instances linked with A instance.
§          Description properties from D instances linked with A instance.
§          Description properties from E instances linked with A instance.





In the server side we could have to following class diagram (we do not care about best practises):

The business object model for this example is the following:




We have to mention important points here:



§          The find method code in the Server Component is:

String queryStr = "select distinct a from A a where a.id = :id";    
Query query = em.createQuery(queryStr).setParameter("id", id);
A a = query.getSingleResult();

§          The extended persistence context is binding to the life cycle of the Client Component.

§          All the relationships from entity A are using Lazy Loading Strategy.

§          When the user interface is rendered in the server side, from A instance, we can get all its relationship instance properties because A is attached to the persistence context.

If this approach is working, Why Do I want to swap from extended persistence context to transactional?



The main reason is the following:

Aurelio - The Guru says: Any change in the database that has been done outside our scope (other user) and affects an entity that appears in the extended persistent context will potentially create inconsistencies once the extended persistence context is NOT notified from DB that an entity that it "caches" has been changed, so by that time the data in that entity is stale (dirty). To workaround this, you have to explicitly refresh() that entity from PC every time you query that, so, what the point of extended persistence context?.

Note:  The solution is not just change from extended to transactional persistence context. In this case happens the following:

When the user interface is rendered, the entity A instance is detached (the transactional persistence context does not exist anymore after finishing the transaction), therefore we can not access to the lazy loading collections linked to entity A instance.

Each vendor solves this situation in a different way (i.e Hibernate: org.hibernate.LazyInitializationException: failed to lazily initialize a collection - no session or session was closed).

Solution - First Approach with transactional persistence context.


The server side we could have to following class diagram:





The business object model for this example is the following:




We have to mention important points here:


§          The code In the Application Service find method is:

String queryStr = "select distinct a from A a LEFT OUTER JOIN FETCH a.b “ +  
               “LEFT OUTER JOIN FETCH a.c ” +
 “LEFT OUTER JOIN FETCH a.d ” +
 “LEFT OUTER JOIN FETCH a.e ” +
 “where a.id = :id";
Query query = em.createQuery(queryStr).setParameter("id", id);
A a = query.getSingleResult();

§          The transactional persistence context is binding to the transaction.

§          All the relationships from entity A are using Lazy Loading Strategy.

§          When the user interface is rendered in the server side, from A instance, we can get all its relationship instance properties because all of them were fetched in the query.

Solution - Second Approach with transactional persistence context.

The server side we could have to following class diagram:




The business object model for this example is the following:



We have to mention important points here:

§          The code In the Application Service find method is:

String queryStr = "select distinct a from A a where a.id = :id";    
Query query = em.createQuery(queryStr).setParameter("id", id);
A a = query.getSingleResult();

§          The transactional persistence context is binding to the transaction.

§          All the relationships from entity A are using Eager Loading Strategy.

§          When the user interface is rendered in the server side, from A instance, we can get all its relationship instance properties because all of them were fetched in the query because are declared Eager.

What a Surprise! These solutions do not work with Hibernate. Hibernate´s bug.

For both approaches we get the next exception:

org.hibernate.HibernateException: cannot simultaneously fetch multiple bags 

After investigating I found this website:

The problem is described as:

“For class X, multiple collection fields are marked for eager fetching: a, b, c; this is not supported by Hibernate in releases after 3.2.x

Hibernate workaround with transactional persistence context.

The server side we could have to following class diagram:










The business object model for this example is the following:

We have to mention important points here: 


§          The code In the Application Service find method is:

String queryStr = "select distinct a from A a where a.id = :id";    
Query query = em.createQuery(queryStr).setParameter("id", id);
A a = query.getSingleResult();

§          The persistence context is binding to the transaction.

§          All the relationships from entity A are using Eager Loading Strategy.

§          Hibernate workaround:

Add a new annotation @Fetch(value = FetchMode.SUBSELECT) in the collections.
@JoinTable(… …
@ManyToMany(fetch = FetchType.EAGER)
@Fetch(value = FetchMode.SUBSELECT)

@JoinTable(… …
@ManyToMany(fetch = FetchType.EAGER)
@Fetch(value = FetchMode.SUBSELECT)

@OneToMany(fetch = FetchType.EAGER, … …)
@Fetch(value = FetchMode.SUBSELECT)

@OneToMany(fetch = FetchType.EAGER, … …)
@Fetch(value = FetchMode.SUBSELECT)
  
§          When the user interface is rendered in the server side, from A instance, we can get all its relationship instance properties because all of them were fetched in the query because are declared Eager.

Saturday 19 September 2009

Something to learn about JEE 6

Java EE 6 Standard Services

The Java EE standard services include the following. Some of these standard services are actually provided by Java SE.
HTTP / HTTPS (over SSL protocol)
The HTTP / HTTPS client-side API is defined by the java.net package.
The HTTP / HTTPS server-side API is defined by the servlet, JSP, JSF interfaces and by the web services support that is a part of the Java EE platform.

Java™ Transaction API (JTA)

The Java Transaction API consists of two parts:
•An application-level demarcation interface that is used by the container and application components to demarcate transaction boundaries.
•An interface between the transaction manager and a resource manager used at the Java EE SPI level.
RMI-IIOP
The RMI-IIOP subsystem is made up of APIs that allow for the use of RMI-style programming that is independent of the underlying protocol, as well as an implementation of those APIs that supports both the Java SE native RMI protocol (JRMP) and the CORBA IIOP protocol. Java EE applications can use RMI-IIOP, with IIOP protocol support, to access CORBA services that are compatible with the RMI programming restrictions. Such CORBA services would typically be defined by components that live outside of a Java EE product, usually in a legacy system. Only Java EE application clients are required to be able to define their own CORBA services directly, using the RMI-IIOP APIs. Typically such CORBA objects would be used for callbacks when accessing other CORBA objects.

Java EE applications are required to use the RMI-IIOP APIs, specifically the narrow method of javax.rmi.PortableRemoteObject, when accessing Enterprise JavaBeans components. This allows enterprise beans to be protocol independent. Note that the most common use of the narrow method is not needed when using dependency injection instead of JNDI lookups; the container will perform the narrow for the application before injecting the object reference. Java EE products must be capable of exporting enterprise beans using the IIOP protocol, and accessing enterprise beans using the IIOP protocol. The ability to use the IIOP protocol is required to enable interoperability between Java EE products, however a Java EE product may also use other protocols.
Java IDL
Java IDL allows Java EE application components to invoke external CORBA objects using the IIOP protocol. These CORBA objects may be written in any language and typically live outside a Java EE product. Java EE applications may use Java IDL to act as clients of CORBA services, but only Java EE application clients are required to be allowed to use Java IDL directly to present CORBA services themselves.
JDBC™ API
The JDBC API is the API for connectivity with relational database systems. The JDBC API has two parts:

·          An application-level interface used by the application components to access a database.

·          A service provider interface to attach a JDBC driver to the Java EE platform. Support for the service provider interface is not required in Java EE products. Instead, JDBC drivers should be packaged as resource adapters that use the facilities of the Connector API to interface with a Java EE product.

The JDBC API is included in Java SE, but this specification includes additional requirements on JDBC device drivers.
Java™ Persistence API
The Java Persistence API is the standard API for the management of persistence and object/relational mapping. This specification provides an object/relational mapping facility for application developers using a Java domain model to manage a relational database. It can also be used in Java SE environments.
Java™ Message Service (JMS)
The Java Message Service is a standard API for messaging that supports reliable point-to-point messaging as well as the publish-subscribe model.
Java Naming and Directory Interface™ (JNDI)
The JNDI API is the standard API for naming and directory access. The JNDI API has two parts:

·          An application-level interface used by the application components to access naming and directory services.

·          A service provider interface to attach a provider of a naming and directory service.

The JNDI API is included in Java SE, but this specification defines additional requirements.
JavaMail™
Java EE platform includes the JavaMail API along with a JavaMail service provider that allows an application component to send Internet mail. The JavaMail API has two parts:

·          An application-level interface used by the application components to send mail.

·          A service provider interface used at the Java EE SPI level.
JavaBeans™ Activation Framework (JAF)
The JAF API provides a framework for handling data in different MIME types, originating in different formats and locations. The JavaMail API makes use of the JAF API. The JAF API is included in Java SE and so is available to Java EE applications.
XML Processing
The Java™ API for XML Processing (JAXP) provides support for the industry standard SAX and DOM APIs for parsing XML documents, as well as support for XSLT transform engines. The Streaming API for XML (StAX) provides a pull-parsing API for XML. The JAXP and StAX APIs are included in Java SE and so are available to Java EE applications.
Java EE™ Connector Architecture
The Connector architecture is a Java EE SPI that allows resource adapters that support access to Enterprise Information Systems to be plugged in to any Java EE product. The Connector architecture defines a standard set of system-level contracts between a Java EE server and a resource adapter.

The standard contracts include:
•A connection management contract that lets a Java EE server pool connections to an underlying EIS, and lets application components connect to an EIS. This leads to a scalable application environment that can support a large number of clients requiring access to EIS systems.
•A transaction management contract between the transaction manager and an EIS that supports transactional access to EIS resource managers. This contract lets a Java EE server use a transaction manager to manage transactions across multiple resource managers. This contract also supports transactions that are managed internal to an EIS resource manager without the necessity of involv­ing an external transaction manager.
•A security contract that enables secure access to an EIS. This contract pro­vides support for a secure application environment, which reduces security threats to the EIS and protects valuable information resources managed by the EIS.
•A thread management contract that allows a resource adapter to delegate work to other threads and allows the application server to manage a pool of threads.
The resource adapter can control the security context and transaction context used by the worker thread.
•A contract that allows a resource adapter to deliver messages to message driv­en beans independent of the specific messaging style, messaging semantics, and messaging infrastructure used to deliver messages. This contract also serves as the standard message provider pluggability contract that allows a message provider to be plugged into any Java EE server via a resource adapt­er.
•A contract that allows a resource adapter to propagate an imported transaction context to the Java EE server such that its interactions with the server and any application components are part of the imported transaction. This contract preserves the ACID (atomicity, consistency, isolation, durability) properties of the imported transaction.
•An optional contract providing a generic command interface between an appli­cation program and a resource adapter.
Security Services
The Java™ Authentication and Authorization Service (JAAS) enables services to authenticate and enforce access controls upon users. It implements a Java technology version of the standard Plugable Authentication Module (PAM) framework and supports user-based authorization. The Java™ Authorization Service Provider Contract for Containers (JACC) defines a contract between a Java EE application server and an authorization service provider, allowing custom authorization service providers to be plugged into any Java EE product.
Web Services
Java EE provides full support for both clients of web services as well as web service endpoints. Several Java technologies work together to provide support for web services. The Java API for XML Web Services (JAX-WS) and the Java API for XML-based RPC (JAX-RPC) both provide support for web service calls using the SOAP/HTTP protocol. JAX-WS is the primary API for web services and is a follow-on to JAX-RPC. JAX-WS offers extensive web services functionality, with support for multiple bindings/protocols. JAX-WS and JAX-RPC are fully interoperable when using the SOAP 1.1 over HTTP protocol as constrained by the WS-I Basic Profile specification.

JAX-WS and the Java Architecture for XML Binding (JAXB) define the mapping between Java classes and XML as used in SOAP calls, and provides support for 100% of XML Schema. The SOAP with Attachments API for Java (SAAJ) provides support for manipulating low level SOAP messages. The Web Services for Java EE specification fully defines the deployment of web service clients and web service endpoints in Java EE, as well as the implementation of web service endpoints using enterprise beans. The Web Services Metadata specification defines Java language annotations that make it easier to develop web services. The Java API for XML Registries (JAXR) provides client access to XML registry servers.
The Java API for RESTful Web Services (JAX-RS) provides support for web services using the REST style. RESTful web services better match the design style of the web and are often easier to access using a wide variety of programming languages. JAX-RS provides a simple high-level API for writing such web services as well as a low-level API that can be used to control all details of the web service interaction.
Management
The Java 2 Platform, Enterprise Edition Management Specification defines APIs for managing Java EE servers using a special management enterprise bean. The Java™ Management Extensions (JMX) API is also used to provide some management support.
Deployment
The Java 2 Platform, Enterprise Edition Deployment Specification defines a contract between deployment tools and Java EE products. The Java EE products provide plug-in components that run in the deployment tool and allow the deployment tool to deploy applications into the Java EE product. The deployment tool provides services used by these plug-in components.

Application Components


The Java EE runtime environment defines four application component types that a Java EE product must support:
Application clients are Java programming language programs that are typically GUI programs that execute on a desktop computer. Application clients offer a user experience similar to that of native applications, and have access to all of the facilities of the Java EE middle tier.
Applets are GUI components that typically execute in a web browser, but can execute in a variety of other applications or devices that support the applet programming model. Applets can be used to provide a powerful user interface for Java EE applications. (Simple HTML pages can also be used to provide a more limited user interface for Java EE applications.)
Servlets, JSP pages, JSF applications, filters, and web event listeners typically execute in a web container and may respond to HTTP requests from web cli­ents. Servlets, JSP pages, JSF applications, and filters may be used to generate HTML pages that are an application’s user interface. They may also be used to generate XML or other format data that is consumed by other application components. A special kind of servlet provides support for web services using the SOAP/HTTP protocol. Servlets, pages created with the JavaServer Pag­es™ technology or JavaServer™ Faces technology, web filters, and web event listeners are referred to collectively in this specification as “web components.” Web applications are composed of web components and other data such as HTML pages. Web components execute in a web container. A web server in­cludes a web container and other protocol support, security support, and so on, as required by Java EE specifications.
Enterprise JavaBeans™ (EJB) components execute in a managed environment that supports transactions. Enterprise beans typically contain the business logic for a Java EE application. Enterprise beans may directly provide web services using the SOAP/HTTP protocol.

Java Technologies

Java Technology
App Client Container
Web Container
EJB Container
Status
EJB 3.1
Ya
Yb
Y
REQ, POPTc
Servlet 3.0
N
Y
N
REQ
JSP 2.2
N
Y
N
REQ
EL 1.1
N
Y
N
REQ
JMS 1.1
Y
Y
Y
REQ
JTA 1.1
N
Y
Y
REQ
JavaMail 1.4
Y
Y
Y
REQ
Connector 1.6
N
Y
Y
REQ
Web Services 1.3
Y
Y
Y
REQ
JAX-RPC 1.1
Y
Y
Y
REQ, POPT
JAX-WS 2.2
Y
Y
Y
REQ
JAX-RS 1.1
N
Y
N
REQ
JAXB 2.2
Y
Y
Y
REQ
SAAJ 1.3
Y
Y
Y
REQ
JAXR 1.0
Y
Y
Y
REQ, POPT
Java EE Management 1.1
Y
Y
Y
REQ
Java EE Deployment 1.2d
N
N
N
REQ, POPT
JACC 1.2
N
Y
Y
REQ
JASPIC 1.0
N
Y
Y
REQ
JSP Debugging 1.0
N
Y
N
REQ
JSTL 1.2
N
Y
N
REQ
Web Services Metadata 2.0
Y
Y
Y
REQ
JSF 2.0
N
Y
N
REQ
Common Annotations 1.1
Y
Y
Y
REQ
StAX 1.0
Y
Y
Y
REQ
Java Persistence 2.0
Y
Y
Y
REQ
Web Beans 1.0
N
Y
Y
Not decided

REQ: required
POPT: proposed optional