Sunday, November 24, 2013

CreateProcess error=87, The parameter is incorrect Using JBoss eap WSConsume and Ant

Trying to run an ant file, when I got this error:

D:\workspace\test\wsclient-ant.xml:33: java.io.IOException: Cannot run program "C:\Java\jdk1.6.0_20\jre\bin\java.exe": CreateProcess error=87, The parameter is incorrect


This error is generated due to this part of my ant file:

<wsconsume 
fork="true"
keep="true"
verbose="true"
destdir="${binDir}"
sourcedestdir="${sourceDir}"
wsdl="${wsdlUrl}"
binding="${basedir}/jaxbCalendarBinding.xml"/>


and the command invoked was :

Command invoked: org.jboss.ws.tools.cmd.WSConsume -k -b D:\workspace\test\jaxbCalendarBinding.xml -o D:\workspace\test\build\bin\classes -s D:\workspace\test\build\src -v http://localhost:8080/MyService/MyService?wsdl

As the command was too long, and I have specified using fork=true that I would like to generate this task in a separate VM, eclipse was enable to do it.

The solution was to put the fork=false.

Thursday, November 21, 2013

Monitoring SOAP Messages : Logging SOAP Request / Response

When developing a web service, we need sometime to see the traffic sent and received between the Server and the client. So we need to watch the SOAP Requests and Responses exchanged.

To do this using metro, we can add just one code line :

Server Side :
com.sun.xml.ws.transport.http.HttpAdapter.dump=true;

Client Side:
com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true;  

As I am using JBoss, so I have added these parameters in the VM :

  •  Dump the SOAP messages on the client side: 

-Dcom.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump=true 

  • Dump the SOAP messages on the Server side:

-Dcom.sun.xml.ws.transport.http.HttpAdapter.dump=true 


Wednesday, November 20, 2013

JBoss7.x JBoss eap 6- NoClassDefFoundError ClassNotFoundException JBoss dependency


JBoss eap 6 comes with implicit and explicit dependencies loading. The implicit dependencies loaded by Jboss as 7 or Jboss eap 6 are listed in this link.
Once your application uses other dependencies, you should explicitly declare them in order to be loaded by JBoss.
You can also explicitely tell JBoss that you will exclude the loading of implicit jars. This is done in the jboss-deployment-structure.xml. An example of an exclusion of JBoss Logger module is explained here.

When we forget to declare a dependency, we will have  NoClassDefFoundError or ClassNotFoundException. Thus you should declare your dependencies in the META-INF/Manifest.MF or WEB-INF/jboss-deployment-structure.xml.




In my application, I use javax.servlet.api and org.jboss.ironjacamar.jdbcadapters. These names should be copied from the module.xml which is located in the specific jboss module.










Tuesday, November 19, 2013

Error in JBoss-deployment-structure.xml cvc-complex-type.2.4.a: Invalid content was found starting with element 'deployment'. One of '{ear-subdeployments-isolated, deployment, sub- deployment, module}' is expected.

When creating a JBoss-deployment-structure.xml, I have this error

 cvc-complex-type.2.4.a: Invalid content was found starting with element 'deployment'. One of '{ear-subdeployments-isolated, deployment, sub-  deployment, module}' is expected.


There is a Bug created for this error in JBoss.

Solution :

Delete the xmlns. 


Migration to JBoss EAP 6: How to migrate your project from old JBoss Version to JBoss EAP 6




Step 1: JBoss AS7 / EAP6 download

Download the JBoss EAP 6

Step 2: Configure the DataSource and the JDBC.

The datasource in JBoss AS7 or EAP6 is configured differently from the previous version. Please see this post, which explain how to do it.

Step 3: Hibernate configuration.

Jboss comes with Hibernate 4 version. Once JBoss detests Persistance.xml file, he add implicitely the Hibernate jars. So there is no need to declare an explicit dependency. But in my application, the used version was Hibernate 3. I don't like to move yet to Hibernate 4. So I have created a Hibernate 3 Module which is quit easy as we have the Hibernate module. Please see this post.

Step 4: Configure the Logging

JBoss comes with a logging module, which really is a good think as we are no more obliged to bundle the log4j jars. In the directory "C:\jboss-eap-6.1\standalone\configuration" you find a file named logging.properties, which you can configure to tell JBoss about your preferences. As this task isn't an urgent one, I will left him to later time. So I just configured JBoss to act as in previous version but this should be configured as JBoss implicitely ass the logging jars. To do this, please refer to the post of exclusion jboss logging.

Step 5: Add explicit dependencies 

JBoss comes with a module concept. The class loading is different from old version. So in JBoss, there is implicit loading and explicit loading. The list of implicit module loading is available here.
An explicit JBoss module, is available in JBoss but is not loaded unless the developer specify it in the WEB-INF/Jboss-deployment-structure.xml or  META-INF/Manifest.mf.
The post is under developemt, so it will be available later with more details.

Step 6: Configure the ClassPath and Resolve the Import errors

When changing the JBoss Runtime in the classpath, different errors appears in the imports. Please refer to this post in order to fix the errors.



Resolved : JBoss Eap 6 Problem in setting JBoss Eap classpath :System lib not found and Errors in the imports

I was facing a problem when migrating to JBoss Eap 6. In fact when changing the Runtime in the Java Build Path from an old one to a JBoss Enterprise Application Plateform6.1 Runtime, I have different errors in the Import. No libraries are found in the added JBoss in the Eclipse Project--> Preferences --> Java Build Path.

It seems that eclipse did not support yet JBoss Eap 6 as it comes with new look and many changes by introducing the module concept. So what to do.

Step 1: Move to JBoss Developer Studio

 Ok as we have trouble using Eclipse. We can chose the JBoss AS 7.1 Runtime. But is it a good idea, as JBoss Eap 6 is supporting JBoss as 7.2. I would like to have clean work. I have decided to work with JBoss Developer Studio which is based finally on eclipse but with some modification to support the new version of JBoss.
So all what you have to do is to login in the Red Hat web Site, and then go to the downloads.


Download the Red Hat JBoss Developer Studio 7:


Step 2 : Add the module to the default classpath Entries

Based on this jboss issue, I have tried the solution given by Rob.


  • Go to Windows --> Preferences --> Server --> Runtime Environments --> Default Classpath Entries 
  • Select JBoss Eap 6 Platform and clic on Add.
  • Give the Root Directory to the Module you would like to include, it may be system modules as your own modules.
  • Clic OK and let it do a full build to add the changements on the projects.



The JBoss EAP 6 Runtime looks like this : I have added the ironjacamar/ Jdbcadapter as I have problem in the import of org.jboss.jca.adapters.jdbc.jdk6.WrappedPreparedStatementJDK6



That's all for this ;)

Saturday, November 16, 2013

Add Hibernate 3 to JBoss AS 7 JBoss EAP 6 Migrate Hibernate 3 to JBoss 7 JBoss eap6

JBoss comes with Hibernate 4 jars. The Hibernate Module is located in

C:\jboss-eap-6.1\modules\system\layers\base\org\hibernate\main

Jboss adds Hibernate if he detects the presence of an @PersistenceUnit, @PersistenceContext annotation, or a <persistence-unit-ref> or <persistence-context-ref> . So we don't need to declare dependency in the jboss-deployment-structure.xml.

But in my case, my application is using Hibernate 3.3, so I have errors in my Hibernate imports as Hibernate 3 differs from Hibernate 4. What to doooooo.


Ok, as I would like to use Hibernate 3 in different application, I prefer to create a new module in JBoss. But this time it will be easier as I have a Hibernate in my modules. So let's start:

Step1:

Create a folder named 3 under "C:\jboss-eap-6.1\modules\system\layers\base\org\hibernate\"



Step2:

Working with Hibernate 3.3, I have downloaded it and put it in the directory 3 with the file module.xml. But I have an error :

javax.persistence.PersistenceException: JBAS011466: PersistenceProvider 'org.hibernate.ejb.HibernatePersistence' not found


In fact 'org.hibernate.ejb.HibernatePersistence' don’t exists at all in Hibernate 3.3, I have upgrated the application to use Hibernate3.6 and the error disappeared. So my hibernate/3 directory looks like this :


And my module.xml associated is this one:


There is no need to add anything to jboss-dependency-structure.xml as it will be loaded implicitely.

Step3: 

Make changes in the persistence.xml

In fact you should delete the provider from persistence.xml, which was org.hibernate.ejb.HibernatePersistence and add this line.

<property name="jboss.as.jpa.providerModule" value="org.hibernate:3" />

The persistence.xml looks like this :




Monday, November 11, 2013

Disable, Exclude JBoss EAP 6 Logging : Exclude Logmanager Module

The JBoss EAP 6 comes with a new look :). It is no more the same directory structure, modules ...


I was trying to move from JBoss as 5 to JBoss 6. After a hard work, I have discovered that the JBoss 6 is End Of Life.


Ok no prblem. Let's move to JBoss EAP6 which uses JBoss as7. Go go go.
After fixing the dataSource configuration, which you can consult in this link. I was happy to deploy for the first time my application. And here Boooom. I get multiple errors ;(.

I have this error message :

[org.jboss.msc.service.fail] (MSC service thread 1-8) MSC000001: Failed to start service jboss.deployment.unit."myapp.war".POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployment.unit."myapp.war".POST_MODULE: JBAS018733: Failed to process phase POST_MODULE of deployment "myapp.war"

Caused by: java.lang.NoClassDefFoundError: javax/mail/internet/AddressException
at java.lang.Class.getDeclaredConstructors0(Native Method) [rt.jar:1.6.0_20]
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) [rt.jar:1.6.0_20]
at java.lang.Class.getConstructor0(Class.java:2699) [rt.jar:1.6.0_20]
at java.lang.Class.newInstance0(Class.java:326) [rt.jar:1.6.0_20]
at java.lang.Class.newInstance(Class.java:308) [rt.jar:1.6.0_20]
at org.apache.log4j.xml.DOMConfigurator.parseAppender(DOMConfigurator.java:247) [log4j-jboss-
Caused by: java.lang.ClassNotFoundException: javax.mail.internet.AddressException from [Module "org.jboss.log4j.logmanager:main" from local module loader @1b64e6a (finder: local module finder @1d62270 (roots: C:\jboss-eap-6.1\modules,C:\jboss-eap-6.1\modules\system\layers\base))]

In fact, as my application uses log4j which is also provided by JBoss. This later will try implicitly to load this module. In the internet, I have discovered that there is an open bug regarding this error. So in order to control this loading, JBoss proposes to use the jboss-deployment-structure.xml. We will not use the Log4j provided by JBoss and use the old method by providing our jar and log4j.xml file.

Step 1 :

Create a jboss-deployment-structure.xml under WEB-INF/  directory.



Step 2 :

Make sure that you put the log4j.jar in the  WEB-INF/lib  directory.


Finally add this parameter "-Dorg.jboss.as.logging.per-deployment=false "in the VM:



Coool it's deploying now :)

Resolved genwsdl-ant.xml:5: taskdef class com.sun.tools.ws.ant.WsGen cannot be found or taskdef class com.sun.tools.ws.ant.WsImport

I have problem when generating the WSDL usinf metro.

The error was :
genwsdl-ant.xml:5: taskdef class com.sun.tools.ws.ant.WsGen cannot be found.

In the classpath defined in the ant file, the jaxws-tools.jar and jaxws-rt.jar should be explicitely mentioned.

<taskdef classname="com.sun.tools.ws.ant.WsGen" name="wsgen">
<classpath path="${metroLib}/jaxws-tools.jar:${metroLib}/jaxws-rt.jar"></classpath>
</taskdef>

Where metroLib= C:/jaxws-ri-2.2.8/jaxws-ri/lib

Another error which accured also was :

You are running on JDK6 which comes with JAX-WS 2.1 API, but this tool requires JAX-WS 2.2 API

To resolve this problem, the jaxb-api.jar and jaxws-api.jar, you should create an endorsed directory in JAVA_Home/jre/lib/endorsed


Configure DataSource Setting in JBoss EAP6

In the previous version of JBoss, the configuration of Datasource was quit easy: the datasource file is defined in the JBoss_Home/server/default/deploy/*-ds.xml, while the JDBC driver is just placed in the JBoss_Home/server/default/lib directory.

In the JBoss EAP 6 is quit different and this is done as below.
In the Jbosseap6/modules, create the directory hierarchy : org/postgresql/main. Put in the main directory the database jdbc. 
In the same directory, create a file named module.xml and put the following code. Make sure to change the JDBC version according to the used one.






I prefer to manually configure the driver by making changes in the standalone.xml located in "C:\jboss-eap-6.1\standalone\configuration" I add Datasource in the Datasources balise and Driver in Drivers.


In my code I have :
private static final String POSTGRES_DS = "java:jboss/datasources/myPostgresDS";

I run after my server and it's OK ! 

Sunday, November 10, 2013

Web service Jbossws cxf: Enhance the Performance to get the service and the port getSertvice and getPort resolved

I was testing a Web Service developed respecting the JAX-WS specification and deployed on Jboss 6. The stack used by the Jboss is the JBossws-cxf 3.4.

Every time I call the getPort, it takes a good laps of time :

myService = new mydevelopedWSService();
System.out.println("take a port takes time " +System.currentTimeMillis());
mydevelopedWS myPort = myService.getmydevelopedWSPort();

In fact what I have find in the internet and in different forum, is that initializing the service involves reading and parsing the wsdl, and getting the port involves the creation of a dynamic port. Oracle specifies that by getting a dynamic client proxy, the application retrieves and interprets the WSDL and dynamically constructs calls. A dynamic proxy client enables a Web service client to invoke a web servicto invoke a Web service based on a service endpoint interface (SEI) dynamically at run-time (without using clientgen, wsconsume in jboss or wsimport in metro). This option does not rely upon a specific service implementation, providing greater flexibility, but also a greater performance hit.

In JBoss, I was trying to reduce this call time, and have seen that by chanding a properti in a file in the deployers, it can reduce considerably the time.

Here is the change to do. Open the file "stack-agnostic-jboss-beans.xml" located in "C:\jboss-6.1.0.Final\server\myconf\deployers\jbossws.deployer\META-INF". This property

<property name="webServiceHost">${jboss.bind.address}</property>
<property name="modifySOAPAddress">false</property>

 The default value is set to true, which means that JBoss is re-writing the soap-address in the WSDL every time we are retrieving it even if the specified address is valid. I have changed this property to false in order to disable this re-write and the application performance was better.

In JBoss eap 6.1, this parameter can be changed in the Standalone.xml located in JBoss-eap-6.1HOME\standalone\configuration.



Sunday, November 3, 2013

Invalid endpoint address in port portName in service ServiceLocator: REPLACE_WITH_ACTUAL_URL


When developing a web service, we often generate WSDL automatically using Wsimport in metro or Wsprovide in Jboss.
When I was trying creating a Wb Service client, I have had this error:
Invalid endpoint address in port portName in service ServiceLocator: REPLACE_WITH_ACTUAL_URL

In fact, in the generated WSDL, there was

<soap:address location="REPLACE_WITH_ACTUAL_URL"></soap:address>

where the Address should be replaced by the service Address

<soap:address location="http://localhost:8080/service/myService.ws"></soap:address>

Saturday, November 2, 2013

How to Get a Heap Dump : Analyze an OutOfMemoryError Java heap space - Part1 -

A Heap Dump is a snapshot of the memory of a Java process at a certain point of time. This snapshot contains information about the Java Objects and Classes in the heap. 

Step 1: Configure the JVM to generate a Heap Dump on an OutofMemory

In order to generate a heap dump when an "java.lang.OutOfMemoryError: Java heap space" exception occurs, the first thing to do is to add -XX:+HeapDumpOnOutOfMemoryError in the VM parameters. I am using Jboss6 server, so belong are the modifications. If you want to have a heap dmp on "CTRL BREAK", you can also add this parameter -XX:+HeapDumpOnCtrlBreak.






When an OutofMemory happens, this will generate a java_pid*.hprof file in the "C:\jboss-6.1.0.Final\bin" directory. This path can be changed in the VM parameters : -XX:HeapDumpPath= path_of_the_dump_file.

Step 2: Force the generation of a Heap Dump 

1- Using JConsole

Another way to generate a heap Dump is by using the JCONSOLE which can be found in the "C:\Java\jdk1.6.0_20\bin" directory.

 Select the dumpHeap operation from the com.sun.management.HotSpotDiagnostic MBean. As parameter p0 you should specify the full path to the heap dump file (exp "C:\hprof_Directory"). The file name should ends with .hprof. Clic to the dumpHeap button, a file will be generated in the choosen directory.


2- Using Memory Analyzer from Eclipse

Another way to have a Heap Dump is to use the Memory Analizer Plugin which can be added to eclipse. Please refer to this link. 
Open the Memory Analysis.






Then acquire a heap dump:


Step 2: Heap Dump Analysis

 

Once you have created your heap dump, you can analyze it using MAT (Memory Analzer). So Open the heap dump and navigate in the different options.




Tuesday, October 29, 2013

Change Soap Request Response Header : java.lang.UnsupportedOperationException / javax.xml.ws.soap.SOAPFaultException: Fault string, and possibly fault code, not set


While testing a web service, I have encountred this error:

javax.xml.ws.soap.SOAPFaultException: Fault string, and possibly fault code, not set
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:146)
...
Caused by: java.lang.UnsupportedOperationException
at java.util.AbstractMap.put(AbstractMap.java:186)
at org.apache.cxf.binding.soap.interceptor.SoapPreProtocolOutInterceptor.setSoapAction(SoapPreProtocolOutInterceptor.java:120)
at org.apache.cxf.binding.soap.interceptor.SoapPreProtocolOutInterceptor.handleMessage(SoapPreProtocolOutInterceptor.java:62)
at org.apache.cxf.binding.soap.interceptor.SoapPreProtocolOutInterceptor.handleMessage(SoapPreProtocolOutInterceptor.java:46)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:255)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:516)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:313)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:265)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:73)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:124)


In fact, I have a client web service code trying to add a SOAP header to a request before calling the Web service.
The problem comes from this part:

BindingProvider bp = (BindingProvider) webServicePort;
bp.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS,
Collections.singletonMap("Cookie", Collections
.singletonList(yourCookieString));

In fact Collections.singletonMap() is used to get an immutable map which cause a UnsupportedOperationException in the getRequestContext().put() method.
Thanks to Ridwan Nizam, we have changed the code :

BindingProvider bp= (BindingProvider) webServicePort;
Map<String, List<String>> singletonMap = new HashMap<String, List<String>>() singletonMap.put("Cookie", Collections.singletonList(yourCookieString));
bp.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS,
singletonMap);

Great, the Exception is then RESOLVED ;)


Biblio:
http://blog.sanaulla.info/2012/11/28/unsupportedoperation-exception-while-using-map-in-java/

Monday, October 28, 2013

Cannot be cast to com.sun.xml.ws.developer.WSBindingProvider: Jboss5 with Metro to Jboss6 /JBoss EAP 6 with JbossWS-Stack

I was working on a migration form Jboss5 using Metro to a Jboss6.1 using the JbossWS-CXF3.4 stack which comes with Jboss.
When I run my application, I have this error :
Cannot be cast to com.sun.xml.ws.developer.WSBindingProvider

In fact, I have a code, where the Webservice Port was cast to com.sun.xml.internal.ws.developer.WSBindingProvider

 WSBindingProvider bp = (WSBindingProvider) webServicePort;

This cast works before with Metro as we use the Sun reference implementation of JAX-WS. As Jboss6.1 comes with CXF stack for web Service, this cast should be adjusted by using javax.xml.ws.BindingProvider.
So the code becomes :

BindingProvider bp = (BindingProvider) webServicePort;

Hope it helps you :)

Sunday, October 6, 2013

Java compiler level does not match the version of the installed java project facet error in eclipse

I have this Error in eclipse for my prject :

java compiler level does not match the version of the installed java project facet

I was using JDK 1.6.0 as a JRE System Library. The solution was to right clic on the project -> Properties and to fix the Project Facet according to the Java version you are using,  here it is 1.6 instead of 1.5 which I have found.


The error is then fixed :) .

Wednesday, September 4, 2013

Hibernate, JPA Interview Questions : Definition, JPA life cycles, Concurrency, Caching



About Hibernate and JPA


Today, I will explain some of Object Relational Mapping terms. Hope that it will be helpful and clear for you. Let's start by explaining what is hibernate.  ORM frameworks provide an abstraction layer over the persistence technology (relational databases like Oracle, MySQL...), allowing developers to focus on the object-oriented details of their domain model rather than lower-level database concerns. JPA is a specification of ORM and Hibernate is just one of many projects that provide an implementation of that specification. It provides an enterprise-level solution for building a persistence tier.



Hibernate framework defines the ways in which the tables and columns of a database are synchronized with the object instances and properties of JavaBeans (the created Entities).

The 4 key interfaces in any JPA application are:

  • The EntityManagerFactory: which represents the configuration for the database in the application.
  • The Entity Manager: It is analogous to a database connection and used to access a database in a particular unit of work. It is used to create and remove persistent entity instances, to find entities by their primary key identity, and to query over all entities.
  • Entity Transaction
  • Query


- Unit of work: The most common pattern in a multi-user client/server application is entitymanager-per-request. In this model, a request from the client is send to the server (where the JPA persistence layer runs), a new EntityManager is opened, and all database operations are executed in this unit of work. Once the work has been completed (and the response for the client has been prepared), the persistence context is flushed and closed, as well as the entity manager object. You would also use a single database transaction to serve the clients request.

- This is the default JPA persistence model in a Java EE environment; injected (or looked up) entity managers share the same persistence context for a particular JTA transaction.

- Persistence Context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. With the persistence context, the entity instances and their lifecycle is managed by a particular entity manager. The scope of this context can either be the transaction or an extended unit of work.

Life Cycle of a JPA Entity

 There are 5 key states that an entity might be in:
  • New / Transient: An object is instantiated but not yet associated with an Entity Manager and has no representation in the database.
  • Managed / Persisted 
  • Detached: Detached entity objects are objects in a special state in which they are not managed by any EntityManager but still represent objects in the database. Detached objects are often returned from a persistence tier to the web layer where they can be displayed to the end-user in some form. Changes can be made to a detached dobject, but these changes won't be persisted to the database until the entity is reassociated with a persistence context (the entity is merged back to an EntityManager to become managed again).
  • Removed


- The merge method's major task is to transfer the state from an unmanaged entity (passed as the argument) to its managed counterpart within the persistence context.
- merge deals with both new and detached entities. Merge causes either INSERT or UPDATE operation according to the sub-scenario (on the one hand it is more robust, on the other hand this robustness needn't be required.)
- persist always causes INSERT SQL operation is executed (i.e. an exception may be thrown if the entity has already been inserted and thus the primary key violation happens.) 

Query Languages 


- HQL (Hibernate Query Language) and JPQL (Java Persistence Query Language) both offer an object-oriented syntax for expressing query that is very similar to SQL. The two languages are interpreted at runtime, which means you cannot use the compiler to verify the correctness and integrity of a query. To adress this limitation, Hibernate includes a Criteria API, which allows queries to be expressed programmatically.

Loading in Hibernate 

- Say you have a parent and that parent has a collection of children. Hibernate now can "lazy-load" the children, which means that it does not actually load all the children when loading the parent. Instead, it loads them when requested to do so. You can either request this explicitly or, and this is far more common, hibernate will load them automatically when you try to access a child.
Lazy-loading can help improve the performance significantly since often you won't need the children and so they will not be loaded.
Also beware of the n+1-problem. Hibernate will not actually load all children when you access the collection. Instead, it will load each child individually. When iterating over the collection, this causes a query for every child. In order to avoid this, you can trick hibernate into loading all children simultaneously, e.g. by calling parent.getChildren().size().

- The fetching strategy is declared in the mapping relationship to define how Hibernate fetch its related collections and entities. There are four fetching strategies
  •  fetch-”join” = Disable the lazy loading, always load all the collections and entities.
  • fetch-”select” (default) = Lazy load all the collections and entities.
  • batch-size=”N” = Fetching up to ‘N’ collections or entities, *Not record*. The batch-size fetching strategy is not define how many records inside in the collections are loaded. Instead, it defines how many collections should be loaded.
  • fetch-”subselect” = Group its collection into a sub select statement.


Caching levels in Hibernate:

-  Caching is all about application performance optimization and it sits between your application and the database to avoid the number of database hits as many as possible to give a better performance for critical applications.
- The first-level cache is the Session cache and is a mandatory cache through which all requests must pass. The Session object keeps an object under its own power before committing it to the database.
- Second level cache is an optional cache and first-level cache will always be consulted before any attempt is made to locate an object in the second-level cache. The second-level cache can be configured on a per-class and per-collection basis and mainly responsible for caching objects across sessions.

Transactions:

- Transaction is based on ACID:
  • Atomicity: If  one step fails, all the other steps fails
  • Consistency: works on a consistent set of data that are hidden from other concurrency running transactions. So, data are left in a clean and consistent state after completion
  • Isolation: Allows different users to work concurrently with the same data without compromise its integrity and correctness. A particular transaction should not be seen by other concurrently running transactions
  • Durability: Persistent changes should not been lost even if the system fails.

- Java transaction API (JTA) specifies standard Java interfaces between a transaction manager and the parties involved in a distributed transaction system: the resource manager, the application server, and the transactional applications.

Concurrency Management in Hibernate


- Concurrency management is done through Pessimistic or Optimistic way. While the application might concurrently access the "same" (persistent identity) business object in two different persistence contexts, the two instances will actually be "different" (JVM identity). Conflicts are resolved at flush/commit time, using an optimistic approach (automatic versioning).

- Hibernate Entity Manager directly uses JDBC connections and JTA resources without adding any additional locking behavior. Hibernate Entity manager adds automatic versioning but dos not lock objects in memory or change the isolation level of the database transaction.

-The only approach that is consistent with high concurrency and high scalability is optimistic concurrency control with versioning. Version checking uses version numbers, or timestamps, to detect conflicting updates (and to prevent lost updates). Hibernate provides for three possible approaches to writing application code that uses optimistic concurrency:
  •  Application version checking
  • Extended entity manager and automatic versioning
  • Detached objects and automatic versioning

 
Biblio:
- http://www.objectdb.com/java/jpa/persistence/detach
- http://spitballer.blogspot.fr/2010/04/jpa-persisting-vs-merging-entites.html
- http://courses.coreservlets.com,  Transaction Management and Automatic Versioning
- http://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/transactions.html
- Book: Spring persistence with Hibernate, Paul Tepper Fisher and Brian D.Murphy

Spring, AOP and Hibernate: Understand Spring

Advantages of layered (multi-tier) architecture :


  • Improved modularity and reuse 
  • Simplifies development
  • Simplifies testing


Layers are essential because they separate some concerns such as presentation and business logic. But without the business tier, there are concerns that are not easily separated. They are called cross cutting concerns such as transactions, security, persistence, logging, etc.
These cross cutting concerns span multiple application components and they must be implemented by sprinkling code throughout the application.

What is Spring


It is a framework for simplifying Java EE plateform application development and enforce the respect of multi-layered development.
By using spring, the code is supported by a backbone that handles dependency wiring, provides aspect-oriented programming (AOP) capability, and generates cohesive configuration metadata that implicitly documents the way your application's pieces fit together.
Spring has enabled the externalization of integration details to an XML configuration file or to express dependency injection through Java annotations.
The mission of spring was first to make the development of Server-side Java applications simpler. It offered a better solution to wiring application dependencies together. For this reason, Spring is often referred to as a Container, meaning that it offers a centralized abstraction for integrating collaborating dependencies via configuration, rather than writing code to handle this task.
Spring's job is to parse your configuration files and then instantiate your managed classes, resolving their interdependencies. The BeanFactory interface defines the core Spring engine that englobe your beans and wires the collaborating dependencies together.
The ApplicationContext extends the BeanFactory interface, providing a set of more robust features. Spring ships with a listener that you can throw into your web.xml file to automatically bootstrap the Spring ApplicationContext and load your configuration file.

Beyond its original IoC roots, Spring provides a pluggable transactional management layer, AOP support, integration points with persistence frameworks, and a flexible web framework called Spring MVC.

Persistence Layer- Spring Hibernate:

The persistence layer often serves as the foundation upon which an application is built. Spring helps to enforce a modular architecture in which the persistence tier is devided into several core layers that contain the following components: 
  • The domain model
  • The Data Access Object (DAO) layer
  • The service facade (or Service Façade)
The domain model represents the entities within an application, defining the manner in which they relate to one another. Each class within the domain model contains the various properties and associations that correlate to columns and relationships within the database.

The DAO layer defines the means for saving and querying the domain model data. The goal of the DAO pattern is to completely abstract the underlying persistence technology and manner in which it loads, saves, and manipulates the data represented by the domain model. The key benefit of the DAO pattern is separation of concerns- the lower-level details of the persistence technology and datasource are abstracted into a series of methods that provide querying and saving functionality. If the persistence technology changes, most of the necessery change would be limited to defining a new DAO implementation, following the same interface. Defining DAO methods in a separate interface is crucial, as it decouples the purpose and contract of the DAO from the actual implementation. Of course, the DAO implementation class will use Hibernate, JPA or whatever persistence technology we have chosen to employ. However, the higher layers of the application are insulated from these details by the DAO interface, giving us portability, consistency, and well-tiered architecture. 

The layer that handles the application business logic is called the Service layer.  It defines an application's public-facing API, combining one or more lower-level DAO operations into a single, cohesive transactional unit. Service facade methods group together multiple DAO methods to accomplish business logic as a single unit of work: this is the concept of a transaction
In Spring, the service layer typically is intended to accomplish three primary tasks:
  • Serve as the core API throught which other layers of your application will interface
  • Define the core business logic, usually calling on one or more DAO methods to achieve this goal
  • Define transactional details for each facade method  


Dependency Injection in Spring:

Spring has become the facto standard for integrating disparate components and frameworks, and has evolved far beyond its dependency injection roots. The purpose of dependency injection is to decouple the work of resolving external software components from your application business logic.
Spring is a lightweight IoC container, meaning that it will assume the responsibility of wiring your application dependencies. Spring allow to tie components together in a loosely coupled manner. This has far-reaching efforts for any application, as it allows code to be more easily refactored and maintained.

Aspect Oriented Programming AOP:

AOP is a strategy that allows behavior to be injected into code in places across an application (a whole slew of classes). The functionality that we would like to apply across the series of classes has little to do with the main purpose of those classes.
Spring ships with transactional support that can be applied to application code through the use of interceptors that enhance your service layer code. An interceptor is code that can be mixed into the excution flow of a method, usually delegating to the interceptor befor and/or after a particular method is invoked. The interceptor encapsulates the behavior of an aspect at a point in a method's execution.
At the basic level, Spring accomplishes AOP through the use of the proxy design pattern.


When you advise your classes by injecting cross-cutting behaviour into various methods, you are not actually injecting code throughout your application (although in a way, that is the net effect of using AOP). Rather you are requesting that srping create a new proxy class, in which functionality is delegated to your existing class along with the transactional implementation.
When you weave cross-cutting behavior into your classes via AOP, Spring is not directly inserting code; rather, it is replacing your classes with proxies that contains your existing code intertwined with the transactional code. Now applying transactional behaviour to a service layer class is a matter of specifying the @Transactional annotation at either the class or method level.


Biblio:
- Book: Spring persistence with Hibernate, Paul Tepper Fisher and Brian D.Murphy

Wednesday, February 20, 2013

Add JPA/Hibernate to an existing eclipse Project

Add JPA/Hibernate Support:


Here we have an existing Eclipse Project, to wich we would like to add JPA/Hibernate support.

Open the project properties:



We can add more details by a simple clic on "Further configuration available. Here, we can add the connection to the database, we we have configured before ( see post Create JPA Project using JPA/Hibernate and MySQL Server  ) 


Resolve Console Configuration Error :

Here, a JPA Error appears : " Console Configuration "" does not exist. ".  In fact, a console configuration describes how the hibernate plugin should configure Hibernate and what configuration files and classpaths are needed to load the POJO's, JDBC Drivers...It is required to make use of query, reverse engineering and code generation.
To setup this Console Configuration,  we should go to the Hibernate Setting in the Project Properties.


Clic details to setup more details about the Console,


When trying to browse the persistence unit, I can't find my persistence.xml. In fact, according to Hibernate, this field is not required if my project have already /META-INF/persistence.xml in its classpath.

We can then see this configuration by opening the Hibernate Configurations View


So we can  see the different tables in the Database and even edit the created configuration.


Object-Relation Mapping- Entities Creation:

Once all is well settled, we can use the Hibernate Plugin to automatically cretae our entities. The mapping between Tables and Entities is then realized.
 


The entities are then created depending on tables available on our database. These entities (Java Classes, POJO) are created, they should be declared in the JPA Persistence Unit:

< class > fr.jpa.model.Vehicule </ class >

Articles les plus consultés