Archive

Archive for July, 2010

Writing Paginated Queries in JPA/Hibernate

July 31st, 2010 Shrihari 1 comment

If you ever had a requirement to implement a feature which would fetch a subset of records in a huge set of tuples from the database. you could end up fine tuning or modifying SQL queries which could be database specific. However you could do it using the JPA or Hibernate provided you know whats the size of page (number of records page should contain) and what page number the user is currently in.

The below code gives you the basic method to retrieve paginated results from a table for a given page, with a page capacity:

public List fetchRecordsForPage(Integer pageIndex, Integer pageSize)
{
   Query query = entityManager.createQuery("select record from DisplayRecord record order by record.id");
   //Specify where to start from
   query.setFirstResult((pageIndex==1)?0:(pageIndex-1)*pageSize);
  //Specify how much records to hold back
  query.setMaxResults(pageSize);
  return query.getResultList();
}

This can be extended to hold criteria based API in Hibernate as well.

Categories: jee-light Tags: ,

Using Embedded JBoss to bulk deploy EJBs

July 12th, 2010 Shrihari No comments

This tip explores implementation of test cases for testing multiple EJB (stateless or stateful) in Embedded JBoss Container. Suppose if a test case is a client for multiple EJBs hosted in multiple jar files, this post will help you configure your test environment to deploy all the EJBs in the Embedded JBoss Container and run test cases against it.
The configuration is simple and is just three stepped process. Assume all the jars containing the EJBs are available as maven artifacts and the tests are deployed as a maven project, the following are sequence of steps:

1) In the project’s pom.xml, specify the maven-dependency-plugin under build/plugins as given below:


<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-ejbs</id>
<phase>process-test-resources</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>my.package</groupId>
<artifactId>my.ejbmodule</artifactId>
<version>1.0.0</version>
<type>ejb</type>
</artifactItem>
<!-- Other EJB module artifacts -->
</artifactItems>
<outputDirectory>${project.build.testOutputDirectory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>

Here the plugin is copying the ejb modules to the target/test-classes/lib before test phase (during process-test-resources phase). If you a non-maven set of ejb module, one could use the maven-antrun-plugin to copy these jar files under target/test-classes/lib in process-test-resources phase.

2) Now since we are using Embedded JBoss as the container and we have the container configurations under src/test/resources, edit the src/test/resources/conf/bootstrap-beans.xml and append the following


<!-- My custom deployment -->
<bean name="ResourcesToDeploy4">
<property name="filter">
<inject bean="DeploymentFilter"/>
</property>
<property name="mainDeployer">
<inject bean="MainDeployer"/>
</property>
<property name="kernel">
<inject bean="jboss.kernel:service=Kernel"/>
</property>
<property name="directoriesByResource">
<list elementClass="java.lang.String">
<value>${jboss.embedded.bootstrap.resource.path}conf/jboss-service.xml/../lib</value>
</list>
</property>
</bean>

Here we are creating a deployment folder ../lib relative to conf/jboss-service.xml, where the ejb modules gets copied as explained in the previous step.

3)  Now in your test-case (implemented either JUnit/TestNG), implement a @BeforeClass annotated method to do the embedded jboss bootstrapping as given below

static MyEJB ejb1 = null;

@BeforeClass
public static void startup() {
Bootstrap bootstrap = Bootstrap.getInstance();
try {
if (!bootstrap.isStarted())
bootstrap.bootstrap();
} catch (DeploymentException deploy)
{}
InitialContext ctx = new InitialContext();
ejb1 =  (MyEJB)ctx.lookup("myejb");
}

All your other ejbs can as well looked upon like specified above.  During test runtime, you can check how embedded jboss is initializing and starting discovered EJB modules. This way one may not need to deployResource for every EJB defined.

Categories: jee-light Tags: , ,

Using Mockito’s Spy to mock hierarchical objects

July 6th, 2010 Shrihari No comments

Mocking in Mockito using mock() method is straight-forward for POJO(s) with no inheritance.  However for objects which are defined as part of class hierarchies, using mock() to alter parental behaviour cannot be implemented. Lets take an example of a base class such as Staff with derived classes: Employee and Contractor as given below:

public class Staff {
    protected String name;
    protected Integer age;
    protected String deptname;
    //other fields, setters and accessors.
}

The Employee/Contractor class look like this

public class Employee extends Staff {
   private String employeeID;
   private Date joinDate;
   //setters and accessors.
}

public class Contractor extends Staff {
    private String contractorID;
    private String fromCompany;
    private Long contractDuration'
    //setters and accessors.
}

Lets now mock Contractor object and stub the name (parental attribute) behaviour:

  Contractor contractor = mock(Contractor.class);
  when(contractor.getName()).thenReturn("John Smith");
  assertEquals(contractor.getName(), "John Smith");

Unfortunately the above code is not able to induce name behaviour using stubbing and assertEquals fails in the above code . Now Mockito provides spy() for creating pseudo mock on real objects. This indeed provides a breather to mock hierarchical objects as show below for the example we have

  Contractor contractor = new Contractor();
  contractor.setName("John Smith");
  Contractor mocked = spy(contractor);
  //other stubbing logic
  assertEquals(contractor.getName(), "John Smith");

This way we can alter functional behaviour for parental properties as well.

Categories: jee-light Tags: