Category Archives: Spring

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

Jersey integration with Spring(Restful web service)

Restful Web service Introduction:
REST-style architectures consist of clients and servers. Clients initiate requests to servers; servers process requests and return appropriate responses. Requests and responses are built around the transfer of representations of resources. A resource can be essentially any coherent and meaningful concept that may be addressed. A representation of a resource is typically a document that captures the current or intended state of a resource.

Jersey  is an open-source, production-ready reference implementation of JAX-RS, the Java API for RESTful Web Services (JSR-311). Jersey makes it easy to create RESTful web services using Java technology.

Building a Small “Ping” restful webservice

Step 1:
Jersey resource:
A Jersey resource is a plain Java class within the context of a web application that uses the @Path annotation to define a URI. The URI represent the relative path to the web context of the deployed app.

public class SayPingResource{
private String param1;

public String getMessage() {
// logic placeholder
return this.param1;

public void setParam1(String param){
@Path: This defines the base URI. Formed with context root and hostname, the resource identifier will be something like
@GET: This means that the following method responds to the HTTP GET method.
@Produces: Defines the response content MIME type as plain/text.

Integration With Spring
Step 2:
Define Jersey Spring servlet in Web.xml

<servlet-name>Jersey Spring</servlet-name>

<servlet-name>Jersey Spring</servlet-name>

Step 3:
Now inside application.xml add the bean declaration for the Restful service

<bean id=”pingbean”  class=”com.test.SayPingResource”>
<property name=”param1″ value=”Success Response”/>

Once the above changes are done, restart/deploy the application. And access with below URI.


Output : “Success Response”

This is my first hands on with Jersey + Spring, Your comments would help me gearing up to write more post on the same 🙂

R Vashi

Log4j Configuration in Spring Application

As we all know how loggers plays a crucial part in managing program flow messages  in the application.
Your application gets  better control on what messages needs to be logged to the files. This can be achieved using the Log Levels. For example., INFO, DEBUG, WARN, ERROR, FATAL etc. For more details on Log4J Framework, Read here @

Now lets see below the LOG4J Configuration in Spring App.

1. In Web.xml add the below entries.

<!– specify the log properties file location –>

<!– spring based logger listener, which will read the log config and start the logger service  –>

2. Add the below inside. WEB-INF/classes/ folder.

# Set root logger level to INFO
log4j.rootLogger=INFO, ET

# ET is set to be a File.

# ET uses PatternLayout.
log4j.appender.ET.layout.ConversionPattern=[ %-5d %-5p %-4rms ] %F : %L – %m%n

3. Now load the logger from the Log factory in your Java class.

public static Logger logger = Logger.getLogger(“ET”);
OR public static Logger logger = Logger.getLogger();“Test message”);

I will try to post a new material on how to use Logging effectively in the application. Wait for that 😉

R Vashi