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.

log4j.category.org.hibernate.SQL= STDOUT // this is as equivalent hibernate.show_sql=true
log4j.category.org.hibernate.type= 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 🙂


Thanks
R Vashi

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

Hi,

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());
em.persist(user);

}


Thanks
R Vashi

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

Hi,

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 dpt.id.deptId 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 dept.id.deptId from Dept dept

Hope this helps.


Thanks,
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
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.

@Path(“/pingservice”)
public class SayPingResource{
private String param1;

@GET
@Produces(“application/plain“)
public String getMessage() {
// logic placeholder
return this.param1;
}

public void setParam1(String param){
this.param1=param;
}
@Path: This defines the base URI. Formed with context root and hostname, the resource identifier will be something like
http://localhost:8080/mysampleapp/service/pingservice
@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>
<servlet-name>Jersey Spring</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Jersey Spring</servlet-name>
<url-pattern>/\*</url-pattern>
</servlet-mapping>

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

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

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

http://localhost:8080/mysampleapp/service/pingservice

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 🙂


Thanks
R Vashi

Log4j Configuration in Spring Application

Hi,
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 @http://logging.apache.org/log4j/1.2/

Now lets see below the LOG4J Configuration in Spring App.

1. In Web.xml add the below entries.

<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
<!– specify the log properties file location –>
</context-param>

<listener>
<!– spring based logger listener, which will read the log config and start the logger service  –>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

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

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

log4j.category.ETlogger=INFO,ET
# ET is set to be a File.
log4j.appender.ET=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ET.File=ETLogger.log
log4j.appender.ET.DatePattern=’.’yyyy-MM-dd
log4j.appender.ET.Threshold=info
log4j.appender.ET.Append=true
log4j.appender.ET.ImmediateFlush=true

# ET uses PatternLayout.
log4j.appender.ET.layout=org.apache.log4j.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();
logger.info(“Test message”);

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


Thanks
R Vashi