Implementing a Unitils DAO testing infrastructure for Spring and JPA on TestNG
Unitils provides an excellant infrastructure for unit testing DAO (and data-service) layers for Spring as IoC Framework on all the component unit testing frameworks such as JUnit 3, JUnit4 and TestNG, without any boilerplate code or coniguration hassles. We will look at establishing a testing infrastructure for Spring with JPA on TestNG frmaework.
Suppose the custom DAO and its implementation definition are like this (with regard to semantics of Spring JPA integration)
package mypackage;
public CustomDAO
{ public List findAll();
public void save(Entity eo);
}
package mypackage;
public CustomDAOImpl implements CustommmDAO
{ @PersistenceContext
private EntityManager em;
//all other method implementations..
....
}
In order to setup a Unitils test infrastructure on TestNG, the following is the class-template:
public class CustomDAOTestCase extends UnitilsTestNG
{ /**
* Injects a test specific application context configuration
*/
@SpringApplicationContext
public ConfigurableApplicationContext createApplicationContext()
{ return new ClassPathXmlApplicationContext("applicationContext-test.xml");
}
@SpringBean("customDAO")
private CustomDAO customDAO;
//all @Test annotated methods..
@Override
protected void unitilsAfterTestTearDown(java.lang.reflect.Method method)
{}
}
for which the following would be the test specific Spring’s application context confguration (applicationContext-test.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="entityManagerFactory" >
<property name="persistenceXmlLocation" value="persistence-test.xml"/>
<property name="persistenceUnitName" value="customservice-test"/>
</bean>
<bean id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<bean id="customDAO" class="mypackage.CustomDAOImpl"/>
</beans>
Look specifically at entityManagerFactory bean definition, org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean allows us to load test specific persistence.xml which could allow us to maintain more than onne persistence context for a sample application.
These two definitions extend the Spring’s JPA capabilities for unit testing DAO on Unitils infrastructure!
Overcoming pitfalls with Query cache in Hibernate
Query caching in Hibernate used to cache query state and results, has multiple shortcomings if, not used judiciously. Some of the common pitfalls include:
(i) Query Cache structural representation is a QueryKey mapped to Object[][] (2-dimensional) and holds majority of persistent object references. QueryKey represents query specific data such as the SQL Query text with parameters (positional/named). QueryKey representation would get deteriorated if parameters represent entity object or a deep rooted object hierarchy.
(ii) If multiple equivalents of load() is invoked, there could potentially create multiple parameter versions of QueryKey containing equivalent duplicate entity objects exist in the cache.
Following are the patterns and practices that could be followed to fix these shortcomings:
1) Decorate org.hibernate.cache.StandardQueryCache and override the put() method to check if a canonical equivalent of a query results object already exist in the Object[][], and assign the same QueryKey if it exists. One needs to implement org.hibernate.cache.QueryCacheFactory also to plug into the Hibernate config.
2) Refactor the code to set entity’s keys as query parameters, rather than setting the entire entity object. Critreia representations should also use identifiers as parameters.
3) Write HQL queries to use identifiers in any substitutable parameters such as WHERE clause, IN clause etc.
4) Use positional parameters over named parameters as it could prevent using string pools.
5) If you are in a single JVM using in memory cache only, use hibernate.cache.use_structured_entries=false in your hibernate configuration.
Hibernate Session’s get() annd load() comparison
These are the differences I could readily understand when I was comparing the runtime behaviour of Hibernate Session’s get and load methods.
a) get() does a database hit as soon as the method is called, load() makes a database hit, only if one of the field in the entity is called.
b) load() should be used when the entity is assured that it exists in the database, else get() should be called. If an non-existent primary key is passed, get() returns a null directly. However passing a non-existing primary key to load() returns you a non-null entity object, but would throw this exception when a field of that entity is referenced: org.hibernate.ObjectNotFoundException: No row with the given identifier exists.
c) calling a field in the entity in load() method after getTransaction().commit(), would throw a LazyInitializationException (could not initialize proxy – no Session).
Dependency Injection’s equivalent Java reflection invocations
As we know that there are 3 types of injections supported by any IoC framework, following are the equivalent function points in the reflection package (java.lang.reflect):
1) Constructor Injection - <T> Constructor.newInstance(Object... initargs) 2) Method Injection - Object Method.invoke(Object obj, Object... args) 3) Field Injection - void Field.set(Object obj, Object value)
Interestingly all these reflection classes are subclasses of java.lang.reflect.AccessibleObject and are final. Also the complete mechanics of Injection semantics hinges on the accessible flag defined in java.lang.reflect.AccessibleObject. Please see javadocs for effective explanation.
Using Google Guice to inject JPA EntityManager
I am working on an persistence example using PrimeFaces, Google Guice and Hibernate. Following are the four steps to inject a JPA EntityManager into the Manager (Appfuse parlance) / DAO Layer:
1) Define META-INF/persistence.xml containing JPA Configuration (similar to hibernate.cfg.xml)
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="persdb" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
...
</properties>
</persistence-unit>
</persistence>
2) Create a startup controller Guice bean
@Controller(name="startupBean", startup=true)
public class StartupBean
{ public StartupBean()
{}
}
3) Create a Google Guice Module
public class MyModule implements Module
{ public void configure(Binder binder)
{ AnnotatedBindingBuilder bindingBuilder = binder.bind(MyDataService.class);
ScopedBindingBuilder scopedBuilder = bindingBuilder.to(MyDataServiceImpl.class);
scopedBuilder.in(SINGLETON);
}
}
and create a context parameter in WEB-INF/web.xml
<context-param>
<param-name>optimus.CONFIG_MODULES</param-name>
<param-value>mypackage.MyModule,org.primefaces.optimus.persistence.JPAModule
</param-value>
</context-param>
Note: org.primefaces.optimus.persistence.JPAModule actually injects the EntityManager reading the META-INF/persistence.xml
4) Create the DaraService implementation containing the injected EntityManager
public class MyDataServiceImpl implements MyDataService { @Inject private EntityManager em; //all methods using JPA entityManager here }
No other configuration xmls to be changed. Ain’t it cool!
Altering JVM’s Garbage-Collection Profiling Format
Every information thread talking about GC dump for a spawned Java VM talks about the command
java -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -verbose:gc -cp $CLASSPATH <fqcn-main-class>
You could look at what is the output format, and what it means here. The timestamps logs the time in seconds and it would be cumbersome to figure out from when the application is running. Hence in order to we tweak in the date forma, we got to use this command instead:
java -XX:+PrintGCDetails -XX:+PrintGCDateStamps -verbose:gc -cp $CLASSPATH <fqcn-main-class>
where the datestamp fomat would be in yyyy-MM-ddTHH:mm:ss.SSS<+-GMT_Difference>.
Apache Lucene core class structure
As part of the Hibernate Search, I happened to get an insight into various core classes of Apache Lucene. Here is the structural model that I feel could be used for reference.

Reducing Cyclomatic Complexity through Refactoring
As put clearly on what adds to cyclomatic complexity in a Java class method here, and to keep the metric around 5-6, following are the refactoring rules we could follow:
1) Keep the method size to less than 25 lines of code.
2) Look at the detail design options of having recursion for intertwined looping constructs with complex logic in case if any.
3) Have fewer points of return by declaring an object of return type and single path of execution to the return statement.
4) Use ternary operations for conditional assignments.
5) Catch exceptions judiciously. Dont catch runtime exceptions, and catch only relevant checked exceptions, throwing other non-relevant exceptions to the caller. This increases cohesions of the method, thus reducing complexity.
Effect of Type Erasure on Casts
As put in the previous blog, runtime type erasures for java generics offer both advantages and annoyances. Lets try exploring its effect on runtime type casting.
Assume we have a code snippet with explicit typecasts and implicit assumptions
private void callMethod(Object array)
{ List<Integer> copiedArray = (List<Integer>)array;
System.out.println("First Element ->"+copiedArray.get(0));
}
private void callingMethod()
{ List<String> stringArray = new ArrayList<String>(2);
stringArray.add(new String("hello"));
callMethod(stringArray);
}
The class containing these method would compile and run without complaints. Reason: During compile time, compiler cannot detect the linked caller and callee parameter types, and during runtime, 'runtime type erasures' ensure the type of a casted object is not maintained in the constant pool. Let us slightly modify the calling method as below.
private void callMethod(Object array)
{ List<Integer> copiedArray = (List<Integer>)array;
System.out.println("First Element ->"+copiedArray.get(0).getClass()); // call a method on the fetched object
}
This would throw ClassCastException during the runtime, as the actual type checking by the JVM is done then.
Type checking for Java Generics – Basics
With introduction of Generics in Java, type checking in Java opened up a can of complex variations and concepts. During the compile type, the compiler enforces stricter type checking for a generics implements. That is
List<String> listOfStrings = new ArrayList<String>(1);
listOfStrings.add(new Integer(1)); //will throw a compilation error
However during the runtime, the JVM doesnt maintain type information about generics, and this is ‘type erasure’. So effectively a code snippet such as this
List<String> listOfStrings = new ArrayList<String>(1); listOfStrings.add("HelloWorld"); String addedElement = listOfStrings.get(0);
would get converted to in
List listOfStrings = new ArrayList(1); listOfStrings.add("HelloWorld"); String addedElement = (String)listOfStrings.get(0);
Behind the scenes, there are 2 passes of compilation, in which the first pass handles the type checking, and in the second pass, the type information is erased and written to the class file.