Category Archives: JSP/Servlets

Using Log4j to log Hibernate queries with values

Hi All,

Hibernate is one of most used ORM framework across the J2EE Applications, It provides many features which helps us to organize the SQL queries in a very easy manner just by playing with java entity bean properties. In this post I will explain the way we can display the named queries in log file including the run time value bindings,

In bigger applications debugging SQL queries is a very crucial thing came into picture, a query containing more SQL Joins is not that easy to debug in case if some misalignment in data found.  To ease that just follow the below steps to enable this sort of hibernate logging in logger(LOG4J).

In Log4j properties add the below two category entries. STDOUT // this is as equivalent hibernate.show_sql=true DEBUG// this basically prints the bound parameters among other things.

Output in Logger file

Hibernate: select emp0_.dept_id as dept2_1_, emp0_.emp_id as emp1_1_, emp0_.emp_id as emp1_0_0_, emp0_.dept_id as dept2_0_0_, emp0_.emp_join_date as emp3_0_0_, emp0_.emp_name as emp4_0_0_, emp0_.bank_name as bank5_0_0_, emp0_.salary as salary0_0_ from Employee emp0_ where emp0_.dept_id=?
2011-12-03 13:08:50,031 DEBUG [main] AbstractBatcher – preparing statement
2011-12-03 13:08:50,031 DEBUG [main] NullableType – binding ‘1’ to parameter: 1
2011-12-03 13:08:50,031 DEBUG [main] AbstractBatcher – about to open ResultSet (open ResultSets: 0, globally: 0)

Hope this helps 🙂

R Vashi

javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist


One of the issues to get your head around in both Hibernate and JPA is how to handle detached entities. In Hibernate one has to deal with the session object and in JPA it is called the persistence context.

An object when loaded in the persistence context is managed by JPA/Hibernate. You can force an object to be detached (ie. no longer managed by Hibernate) by closing the EntityManager or in a more fine-grained approach by calling the detach() method.

So it is very time consuming to debug when you face “Detached entity” exception being thrown by JPA/HIbernate. THere are few possible things you should look for.

1. See if you trying to persist or merge an entity which has the same id as another entity, and which is already present in the PersistenceContext.

2. See if you you’ve specified that @Id is GENERATED by Hibernate. Do not set an ID before you save/persist it. Hibernate looks at the Entity you’ve passed in and assumes that because it has its PK populated that it is already in the database.
save() and persist() do almost the same things with slightly different semantics . persist() is JPA compliant and save() is a carryover from the original Hibernate. Mainly, save() returns the PK and persist() does not. However, both will generate the PK before the actual SQL INSERT happens (if the PK is generated and not assigned).

One workaround I did to solve this was to first find and then save the entity. See below example.

@PersistenceContext(unitName = “JPAUnit”)
private EntityManager em;

public void saveDetails(EntityManager em, User user){
em.find(User.class, user.getId());


R Vashi

JPA/Hibernate:- java.lang.IllegalStateException: No data type for node


Few days back I got struck with one of the hiberante exception I was facing while running one named query.

Exception Details:

Exception in thread "main" java.lang.IllegalStateException: No data type for node: org.hibernate.hql.ast.tree.IdentNode
 \-[IDENT] IdentNode: 'dpt' {originalText=dpt}

As I haven’t work as that extensive on JPA, due to that I was not able to catch early the root cause of this exception 😦 , After carefully examining around all the entity classes, Then I came to know about the orgin of this issue.

Named Query which was used to fetch the department details.(The below query scenario represent imaginary situation)

select from Dept dept

The root cause was the alias name being used for the Entity reference. Alias name ‘dept‘ should have been used in the SELECT Clause of the HQL. Where as it was referring to ‘dpt‘ and was causing this exception.

Right named query:

select from Dept dept

Hope this helps.

R Vashi

Building a Basic Web service using JAX-WS

Web Service: A web service is a service which runs over XML Data exchange in the form of SOAP Request and SOAP Response.  The advantage we got over web service is the communication with different language platforms e.g. Java, .net, C++, PHP   etc.  Web services are playing a crucial part in SOA (Service Oriented Architecture) which is again a very broad term and one of the successful architecture accepted by many enterprise level applications today. Let’s end the definition part here and move now to Web Service development part. (Hope the intro have made you clear the basic concept of Web Services if not please do Google more on web services 🙂 ).

Develop a Simple Web Service

To develop a web service there are 2 types of approaches we can follow.

1.       Contract First Approach.

2.       Code First Approach

Contract First Approach: This approach works on the basis of WSDL, and require a very good knowledge of WSDL, XML, XSD.  Once you expertise the web services then you can apply some hand on this approach. For this post I will describe how to build a web service using 2nd Approach.

Code First

This approach starts with the very core level of code writing. I mean by writing a Java Class and defining all the properties of web services i.e. ports, operation, endpoints etc.

Lets Develop a Ping Web Service: This web service will simply return a greeting message with Current date and time.

First of All write a Java Class:

package com.webservice.sample;

import javax.jws.WebMethod;

import javax.jws.WebService;

import javax.jws.soap.SOAPBinding;

import java.util.Date;

@WebService(name=”PingServer”, serviceName=”PingServer”,portName=”PingServerPort”, targetNamespace=”com.webservice.pingserver”)

@SOAPBinding(style=SOAPBinding.Style.DOCUMENT,use=SOAPBinding.Use.LITERAL, parameterStyle=SOAPBinding.ParameterStyle.WRAPPED)

public class PingServer {


public String getPingStatus(){

return “Hi!! I am active :” + new Date().getTime();




@WebService :

Name: This Defines a name of web service
serviceName: This Defines a name of web service Endpoint interface

portName: This defines the name of the port

targetNamespace: Define a namespace for your web service, if no name specified, Compiler will take a default name space in the reverse order of you package name.


Style       =Defines a Soap Styel e.g SOAPBinding.Style.DOCUMENT,

Use     = Specify a SOAP Message format e.g SOAPBinding.Use.LITERAL, 

parameterStyle =defines how Web service request/reply messages are interpreted by a Web service provider/consumer. Quite simply, "wrapper" style tells the Web service provider that the root element of the message (also called "wrapper element") represents the name of the operation and it is not part of the payload. This also means that children of the root element must map directly to parameters of the operation's signature. The "non-wrapper" style (also sometimes called "bare"), does not make this assumption; in this case the entire message will be passed to the service operation. The reply message is handled in a similar way.

@WebMethod : This specify the method which is exposed to web service(operation)

in case if you are passing any arguments to the web service method.
You can use @WebParam(name=”argumentName”) annotation to comply with the schema. Otherwise generic “in0”, “in1” names will be used in WSDL for input arguments.

Generating the Web Service Artifacts

Now we need to create the artifacts of the web services. There is tool called WSGEN, This tools reads the Service Endpoint interface   and generate the WSDL and XML Schema for the web service which needs to be published.

To Run the tool first of all compile the Web service which we have created above. And open the command console and move the compiled directory e.g “/bin” dir. And run the below command.

wsgen –cp .  com.webservice.sample -wsdl

Once you run the tool you will notice the creation of WSDL and XDS creation in the “/bin” directory.

Now Let’s publish the Web Service.

In this part we will use the EndPoint class to publish the web service using a lightweight web server.

public class TestPublisher {

public static void main(String[] args) {

Endpoint.publish(“http://localhost:8011/service/pingserver”, new PingServer());


Call the publish method to publish the web service using FQN of the web service URL and the Service endpoint interface.

Endpoint.publish(URL, Object);

Once you run the Publisher. Go to Run -> Internet Explorer

And open the URL


If you are able to see the WSDL, Time to cheer!!!!! now… As the Web service has been published successfully.

[Note] Quit the Publisher Class to stop that Lightweight Web Server.

I will explain how to write a web service client to test the web service in my Next Post. Please give your suggestions or feedback.

R Vashi

Useful JVM tunings

Categories of Java HotSpot VM Options

Standard options recognized by the Java HotSpot VM are described on the Java Application Launcher reference pages for Windows, Solaris and Linux. This document deals exclusively with non-standard options recognized by the Java HotSpot VM:

* Options that begin with -X are non-standard (not guaranteed to be supported on all VM implementations), and are subject to change without notice in subsequent releases of the JDK.
* Options that are specified with -XX are not stable and are not recommended for casual use. These options are subject to change without notice.

Some Useful -XX Options

Default values are listed for Java SE 6 for Solaris Sparc with -server. Some options may vary per architecture/OS/JVM version. Platforms with a differing default value are listed in the description.

* Boolean options are turned on with -XX:+<option> and turned off with -XX:-<option>.
* Numeric options are set with -XX:<option>=<number>. Numbers can include ‘m’ or ‘M’ for megabytes, ‘k’ or ‘K’ for kilobytes, and ‘g’ or ‘G’ for gigabytes (for example, 32k is the same as 32768).
* String options are set with -XX:<option>=<string>, are usually used to specify a file, a path, or a list of commands

Flags marked as manageable are dynamically writeable through the JDK management interface ( API) and also through JConsole. In Monitoring and Managing Java SE 6 Platform Applications, The manageable flags can also be set through jinfo -flag.

The options below are loosely grouped into three categories.

* Behavioral options change the basic behavior of the VM.
* Performance tuning options are knobs which can be used to tune VM performance.
* Debugging options generally enable tracing, printing, or output of VM information.

1. Behavioral Options

Option and Default Value

-XX:-AllowUserSignalHandlers    Do not complain if the application installs signal handlers. (Relevant to Solaris and Linux only.)

-XX:AltStackSize=16384    Alternate signal stack size (in Kbytes). (Relevant to Solaris only, removed from 5.0.)

-XX:-DisableExplicitGC    Disable calls to System.gc(), JVM still performs garbage collection when necessary.

-XX:+FailOverToOldVerifier    Fail over to old verifier when the new type checker fails. (Introduced in 6.)

-XX:+HandlePromotionFailure    The youngest generation collection does not require a guarantee of full promotion of all live objects. (Introduced in 1.4.2 update 11) [5.0 and earlier: false.]

-XX:+MaxFDLimit    Bump the number of file descriptors to max. (Relevant  to Solaris only.)

-XX:PreBlockSpin=10    Spin count variable for use with -XX:+UseSpinning. Controls the maximum spin iterations allowed before entering operating system thread synchronization code. (Introduced in 1.4.2.)

-XX:-RelaxAccessControlCheck    Relax the access control checks in the verifier. (Introduced in 6.)

-XX:+ScavengeBeforeFullGC    Do young generation GC prior to a full GC. (Introduced in 1.4.1.)

-XX:+UseAltSigs    Use alternate signals instead of SIGUSR1 and SIGUSR2 for VM internal signals. (Introduced in 1.3.1 update 9, 1.4.1. Relevant to Solaris only.)

-XX:+UseBoundThreads    Bind user level threads to kernel threads. (Relevant to Solaris only.)

-XX:-UseConcMarkSweepGC    Use concurrent mark-sweep collection for the old generation. (Introduced in 1.4.1)

-XX:+UseGCOverheadLimit    Use a policy that limits the proportion of the VM’s time that is spent in GC before an OutOfMemory error is thrown. (Introduced in 6.)

-XX:+UseLWPSynchronization    Use LWP-based instead of thread based synchronization. (Introduced in 1.4.0. Relevant to Solaris only.)

-XX:-UseParallelGC    Use parallel garbage collection for scavenges. (Introduced in 1.4.1)

-XX:-UseParallelOldGC    Use parallel garbage collection for the full collections. Enabling this option automatically sets -XX:+UseParallelGC. (Introduced in 5.0 update 6.)

-XX:-UseSerialGC    Use serial garbage collection. (Introduced in 5.0.)

-XX:-UseSpinning    Enable naive spinning on Java monitor before entering operating system thread synchronizaton code. (Relevant to 1.4.2 and 5.0 only.) [1.4.2, multi-processor Windows platforms: true]

-XX:+UseTLAB    Use thread-local object allocation (Introduced in 1.4.0, known as UseTLE prior to that.) [1.4.2 and earlier, x86 or with -client: false]

-XX:+UseSplitVerifier    Use the new type checker with StackMapTable attributes. (Introduced in 5.0.)[5.0: false]

-XX:+UseThreadPriorities    Use native thread priorities.

-XX:+UseVMInterruptibleIO    Thread interrupt before or with EINTR for I/O operations results in OS_INTRPT. (Introduced in 6. Relevant to Solaris only.)

2. Performance Options

Option and Default Value
-XX:+AggressiveOpts    Turn on point performance compiler optimizations that are expected to be default in upcoming releases. (Introduced in 5.0 update 6.)

-XX:CompileThreshold=10000    Number of method invocations/branches before compiling [-client: 1,500]

-XX:LargePageSizeInBytes=4m    Sets the large page size used for the Java heap. (Introduced in 1.4.0 update 1.) [amd64: 2m.]

-XX:MaxHeapFreeRatio=70    Maximum percentage of heap free after GC to avoid shrinking.

-XX:MaxNewSize=size    Maximum size of new generation (in bytes). Since 1.4, MaxNewSize is computed as a function of NewRatio. [1.3.1 Sparc: 32m; 1.3.1 x86: 2.5m.]

-XX:MaxPermSize=64m    Size of the Permanent Generation.  [5.0 and newer: 64 bit VMs are scaled 30% larger; 1.4 amd64: 96m; 1.3.1 -client: 32m.]

-XX:MinHeapFreeRatio=40    Minimum percentage of heap free after GC to avoid expansion.

-XX:NewRatio=2    Ratio of new/old generation sizes. [Sparc -client: 8; x86 -server: 8; x86 -client: 12.]-client: 4 (1.3) 8 (1.3.1+), x86: 12]

-XX:NewSize=2.125m    Default size of new generation (in bytes) [5.0 and newer: 64 bit VMs are scaled 30% larger; x86: 1m; x86, 5.0 and older: 640k]

-XX:ReservedCodeCacheSize=32m    Reserved code cache size (in bytes) – maximum code cache size. [Solaris 64-bit, amd64, and -server x86: 48m; in 1.5.0_06 and earlier, Solaris 64-bit and and64: 1024m.]

-XX:SurvivorRatio=8    Ratio of eden/survivor space size [Solaris amd64: 6; Sparc in 1.3.1: 25; other Solaris platforms in 5.0 and earlier: 32]

-XX:TargetSurvivorRatio=50    Desired percentage of survivor space used after scavenge.

-XX:ThreadStackSize=512    Thread Stack Size (in Kbytes). (0 means use default stack size) [Sparc: 512; Solaris x86: 320 (was 256 prior in 5.0 and earlier); Sparc 64 bit: 1024; Linux amd64: 1024 (was 0 in 5.0 and earlier); all others 0.]

-XX:+UseBiasedLocking    Enable biased locking. For more details, see this tuning example. (Introduced in 5.0 update 6.) [5.0: false]

-XX:+UseFastAccessorMethods    Use optimized versions of Get<Primitive>Field.

-XX:-UseISM    Use Intimate Shared Memory. [Not accepted for non-Solaris platforms.] For details, see Intimate Shared Memory.

-XX:+UseLargePages    Use large page memory. (Introduced in 5.0 update 5.) For details, see Java Support for Large Memory Pages.

-XX:+UseMPSS    Use Multiple Page Size Support w/4mb pages for the heap. Do not use with ISM as this replaces the need for ISM. (Introduced in 1.4.0 update 1, Relevant to Solaris 9 and newer.) [1.4.1 and earlier: false]

-XX:+StringCache    Enables caching of commonly allocated strings.

-XX:AllocatePrefetchLines=1    Number of cache lines to load after the last object allocation using prefetch instructions generated in JIT compiled code. Default values are 1 if the last allocated object was an instance and 3 if it was an array.

-XX:AllocatePrefetchStyle=1    Generated code style for prefetch instructions.
0 – no prefetch instructions are generate*d*,
1 – execute prefetch instructions after each allocation,
2 – use TLAB allocation watermark pointer to gate when prefetch instructions are executed.

3. Debugging Options

Option and Default Value
-XX:-CITime    Prints time spent in JIT Compiler. (Introduced in 1.4.0.)

-XX:ErrorFile=./hs_err_pid<pid>.log    If an error occurs, save the error data to this file. (Introduced in 6.)

-XX:-ExtendedDTraceProbes    Enable performance-impacting dtrace probes. (Introduced in 6. Relevant to Solaris only.)

-XX:HeapDumpPath=./java_pid<pid>.hprof    Path to directory or filename for heap dump. Manageable. (Introduced in 1.4.2 update 12, 5.0 update 7.)

-XX:-HeapDumpOnOutOfMemoryError    Dump heap to file when java.lang.OutOfMemoryError is thrown. Manageable. (Introduced in 1.4.2 update 12, 5.0 update 7.)

-XX:OnError=”<cmd args>;<cmd args>”    Run user-defined commands on fatal error. (Introduced in 1.4.2 update 9.)

-XX:OnOutOfMemoryError=”<cmd args>;
<cmd args>”     Run user-defined commands when an OutOfMemoryError is first thrown. (Introduced in 1.4.2 update 12, 6)

-XX:-PrintClassHistogram    Print a histogram of class instances on Ctrl-Break. Manageable. (Introduced in 1.4.2.) The jmap -histo command provides equivalent functionality.

-XX:-PrintConcurrentLocks    Print java.util.concurrent locks in Ctrl-Break thread dump. Manageable. (Introduced in 6.) The jstack -l command provides equivalent functionality.

-XX:-PrintCommandLineFlags    Print flags that appeared on the command line. (Introduced in 5.0.)

-XX:-PrintCompilation    Print message when a method is compiled.

-XX:-PrintGC    Print messages at garbage collection. Manageable.

-XX:-PrintGCDetails    Print more details at garbage collection. Manageable. (Introduced in 1.4.0.)

-XX:-PrintGCTimeStamps    Print timestamps at garbage collection. Manageable (Introduced in 1.4.0.)

-XX:-PrintTenuringDistribution    Print tenuring age information.

-XX:-TraceClassLoading    Trace loading of classes.

-XX:-TraceClassLoadingPreorder    Trace all classes loaded in order referenced (not loaded). (Introduced in 1.4.2.)

-XX:-TraceClassResolution    Trace constant pool resolutions. (Introduced in 1.4.2.)

-XX:-TraceClassUnloading    Trace unloading of classes.

-XX:-TraceLoaderConstraints    Trace recording of loader constraints. (Introduced in 6.)

-XX:+PerfSaveDataToFile    Saves jvmstat binary data on exit.


R Vashi

Download a file using Response headers

Hi All,

We sometime struggle implementing a functionality to download a file through browser download dialog window.

The below example will demonstrate the way we can download a file using response headers.

There are few steps you need to follow:

Step 1: First of all set the Content Type, for example if you want to set the file extension to Excel then.


Step 2: Now in this step we will set the response headers so that the browser can display the save and open prompt for the file.
Content-disposition is an extension to the MIME protocol that instructs a MIME user agent on how it should display an attached file.When Internet Explorer/Mozilla/any browser receives the header, it raises a File Download dialog box whose file name box is automatically populated with the file name that is specified in the header.

response.setHeader(“Content-Disposition”, “attachment;filename=” + MYFILE+”_TEST”+version_no+”.xls”)

Step 3: In this step we will add the data to the file which we are going to download.

response.getOutputStream().print(myData); // here my data is CSV formatted data

Step 4: Now access the servlet/jsp, the moment it loads you will see download window asking for save/open a file.

e.g http://localhost:8080/myapp/downlodReport

Hope this helps.

R Vashis

Creating JNDI Data Source in Tomcat to Connect Oracle Data Source

Hi All,

In this article I will show how to create a JNDI data source in Tomcat.

When building a J2EE based application,  the daunting task we see first is the DB connectivity management. And then the Connection Pool implementation comes into the practise.  But there is always lots of issues observed by configuring data sources in web application servers.

The normal practise which every development team does is to provide the data source configuration(user/password, DB URL etc), add the JDBC drivers, define various settings for pool management.

Tomcat allows us to define this configuration context wise or application reference wise.

To define the Web Server Context wise. Simply go to [TOMCAT_HOME]/conf/server.xml, and add the the below configuration.

<Context docBase=”myapp” path=”/myapp” reloadable=”true” source=”org.eclipse.jst.j2ee.server:myapp”>
<Resource auth=”Container” connectionCacheName=”TestCache” connectionCacheProperties=”{MaxStatementsLimit=0, MinLimit=0, InitialLimit=0, ValidateConnection=true, ConnectionWaitTimeout=600, MaxLimit=10000}” connectionCachingEnabled=”true” driverclassname=”oracle.jdbc.driver.OracleDriver” factory=”oracle.jdbc.pool.OracleDataSourceFactory” name=”DataSourceName” scope=”Shareable” type=”oracle.jdbc.pool.OracleDataSource” url=”jdbc:oracle:thin:@HOST_IP:PORT:SID” password=”pa$$w0rd” user=”pooluser”/>

To Define the configuration for application scope,
Simply create Context.xml and add the below configuration.

<Resource name=”jdbc/DataSourceName” auth=”Container”
url=”jdbc:oracle:thin:@HOST_IP:PORT:SID” password=”pa$$w0rd” user=”pooluser”

path – this defines the name of the application
connectionCacheProperties- defines the variuos connection pool settings
driverclassname – defines the driver manager class name
name – DataSourceName [JNDI Name]
URL – DB host URL
user – connection pool user
password – password
type – defines the type of data source

Once the configuration is added,  add the Context.xml into META-INF folder of Applications .WAR file.
Now in Your JSP/Servlet/Data Access Layer add the below code to get the Connection from Data Source via JNDI lookup.

DataSource ds = (DataSource) ic.lookup(“java:comp/env/jdbc/DataSourceName”);
Connection c = ds.getConnection();

[NOTE] This only works with Tomcat, as every Web Application server have their own implementation for the same.

R Vashi