Category Archives: Core Java

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

Configure Log4j in simple steps

Hi All,

The logging framework always plays a crucial part in your application. In this post i will explain how to configure Log4J in simple steps.
Step1:

Put the Log4j jars file in classpath.

Step 2:
Create a log4j properties | xml file.

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

log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=%d %p [%t] %C{1} - %m\n

log4j.category.org.hibernate.SQL= STDOUT
log4j.category.org.hibernate.type= STDOUT

XML

<!--?xml version="1.0" encoding="UTF-8"?>

Step 3:
Write a program to load and start the logging in application

private static Logger logger = Logger.getLogger(TestJPAConfiguration.class);

public static void main(String[] args) {

//this is for basic loading
BasicConfigurator.configure();

//Use property configurator to explicit load the log4j properties file.
//PropertyConfigurator.configure(“log4j.properties”);

//in case of using XML config, Use DOM Configurator
// DOMConfigurator.configure(“log4j.xml”);

logger.info(“Log4J Configured  successfully”);

}

Hope this helps. 🙂


Thanks
R Vashi

Using ValidationEventHandler while converting XML to Java object in JAXB

Hi All,

JAXB as we know is an API  for XML Binding. It is heavily used in JAX-WS web services as a binding standard. XML Data binding describes the conversion of data between its XML and Java representations.

So this post talks about the phase when we convert the XML Data to its corresponding Java objects. It seems easy as just by calling the unmarshaller.unmarshal method. But what goes behind the scene is not that quite easy.

And think about a scenario where you have data payload in XML format of more than 3mb and just seeing some “NullPointerException” during un-marshalling will make you go mad(specially which I had felt so many times 🙂 ).

So to tackle this lets first of all understand what JAXB does during un-marshalling. JAXB reports validation of data through events.  It uses a handler called as “ValidationEventHandler“, And this handler represent an instance of “ValidationEvent” and provides many details about the un-marshalling related issues.

Lets see in an example(I am taking the base example I have posted in this post) https://rocksolutions.wordpress.com/2010/08/04/sample-on-jaxb-using-eclipse/

Step 1: Create a Custom Handler Class

import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;

public class CustomValidationEventHandler implements ValidationEventHandler {

    public boolean handleEvent(ValidationEvent event) {
        System.out.println("Event");
        System.out.println("Severity:  " + event.getSeverity());
        System.out.println("Message:  " + event.getMessage());
        System.out.println("Linked Exception:  " + event.getLinkedException());
        System.out.println("Locator:::");
        System.out.println("    Line Nbr:  " + event.getLocator().getLineNumber());
        System.out.println("    Column Nbr:  " + event.getLocator().getColumnNumber());
        System.out.println("    Offset:  " + event.getLocator().getOffset());
        System.out.println("    Objct:  " + event.getLocator().getObject());
        System.out.println("    Node:  " + event.getLocator().getNode());
        System.out.println("    URL:  " + event.getLocator().getURL());
        return true;
    }

}


Step 2: Register the Handler with the Unmarshller

unmarshaller.setEventHandler(new CustomValidationEventHandler());


Now run the program and you will see the somewhat similar output.

Severity:  1
Message:  cvc-maxLength-valid: Value 'TESTPRODUCT' with length = '10' is not facet-valid with respect to maxLength '8' for type 'stringWithMaxSize8'.
Linked Exception:  org.xml.sax.SAXParseException: cvc-maxLength-valid: Value 'TESTPRODUCT' with length = '10' is not facet-valid with respect to maxLength '8' for type 'stringWithMaxSize8'.
Locator:::
    Line Nbr:  3
    Column Nbr:  12
    Offset:  -1
    Object:  null
    Node:  null
    URL:  null

One thing which I have observed is that the Node and URL properties are not always available to be set on the locator. This is something which I am investigating will sure post the reasons on the same, would appreciate if somebody share the reason.

Please do share your thoughts about this Post 🙂


Thanks
R Vashi

Welcome to Java7 Quick tour

Hi,

While browsing some information about Java 7, I came across a very nice blog covering few major changes in Java 7. Would like to share with all my blog users. Here it goes..

The first example will show switch with String, previously this functionality was only possible  with Enums and integer values. In actual fact the JDK retrieves the hashcode for the String which is an integer. Below is an example of this feature.

String drink=”coffee”;
switch (drink){
case “coffee”:
System.out.println(“So you need milk”);
break;
case “juice”:
System.out.println(“So you need sugar”);
break;
case “refrigerate”:
System.out.println(“So you need ice”);
break;
default:
System.out.println(“unknown drink “);
break;
}
I will now show you the ARM, Automatic Resource management, you don’t need to concern yourself with the resources that will be used in your program because it will automatically close when it exits the Try block. For this just implement the interface java.lang.AutoCloseable, the only method is the Close, The AutoCloseable is the better option than Closeable because an exception is not thrown when you close the resource, in the second picture we can see this.
public void copyFile(File original, File copy) throws FileNotFoundException, IOException {
try (
InputStream in = new FileInputStream(original);
OutputStream out = new FileOutputStream(copy)) {
byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) >= 0) {
out.write(buf, 0, n);
}
}// it is automatically close
}
The multi-try, for some people is the most important feature in this version, it now allows many exceptions inside the catch block just separate with a “|” pipe.
ExemploARM arm=new ExemploARM();
try {
arm.copyFile(origem, destino);
catch (FileNotFoundException | IOException ex) {
ex.printStackTrace();
System.out.println(“It’s can’t copy file”);
}
using multy-try
In Java 7 there are some improvements to Generics and collections making it easy to make this type Object. Now it is possible to make generic collections easily with the  diamond operator “<>”
List<Object> diamond=new ArrayList<>(); // diamond
List<Drink> Drinks;
Map<String, List<Drink>> maps=new HashMap<>();
maps.put(“diamond”, drinks=new ArrayList<>() );
maps.put(“other example”, new ArrayList<Bebida>() );
maps.put(“erro”, new ArrayList<>() );
[/code] Picture 4: diamond
Talking more about generic collections there is the annotation @SafeVarargs for ensuring this method is safe.
 Applying this annotation to a method or constructor suppresses unchecked warnings about a non-reifiable variable-arity (vararg) type and suppresses unchecked warnings about parameterized array creation at call sites.
@SafeVarargs
static List asList (T… elements) {
System.out.println(elements);
return null;
}
@SafeVarargs
static void varags(List… stringLists) {
Object[] array = stringLists;
List tmpList = Arrays.asList(42);
array[0] = tmpList; //run with warning
String s = stringLists[0].get(0); // ClassCastException
}
@SafeVarargs
The digit separator allows for good understand when writing big numbers in java code, the only rule is you can’t separate the last and the first number, now you can write separator numbers with the character “_” it is also possible to write Double values and Float values, for example, for the JDK is equals 22 and 2_2. There is also literal in binary, which is most important when programming in embedding devices,  just put “ob” (zero and b) in front of a number, this Features can also use the separator.
long longPrimitive=9_999_999_99;
Long longObjete=9__3234_300l;
double doublePrimitive=232_32.32_12d;
Double doubleObjeto=88_32.32_12d;
int binA=0b01_01;
int binB=0b0101_0111;
if(2222==22_22){
System.out.println(“equals values”);
}
if(binA==5){
System.out.println(“equals binary values”);
}
picture 5: using separator and literal binary.
Other feature interesting is try with resource now it possible instantiate one variable if it does not generate an exception.
BufferedWriter writer=null;
try {
writer = Files.newBufferedWriter(arquivo, charset);
writer.write(s, 0, s.length());
catch (IOException x) {
System.err.format(“IOException: %s%n”, x);
}
Picture 6: before was necessary create the variable
try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {
writer.write(s, 0, s.length());
catch (IOException x) {
System.err.format(“IOException: %s%n”, x);
}
Picture 7: after using try with resource in java 7 

Some more features..

 

[Source]
http://weblogs.java.net/blog/otaviojava/archive/2011/08/21/welcome-java-7-part-2-jsr-334-coin-0
http://marxsoftware.blogspot.com/2011/03/jdk-7-new-interfaces-classes-enums-and.html


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