Saturday, January 14, 2012

Spring Roo 1.1 Cookbook review by Shekhar Gulati

Many thanks to Shekhar for reviewing Spring Roo 1.1 Cookbook :)

You can visit Shekhar's blog and read the complete review here :

View and add dynamic finder methods

A dynamic finder method is a finder method for which you don't need to write a JPA query.

Download ch03_persistent_entities.roo script from the source code that accompanies Spring Roo 1.1 Cookbook:

The script sets up Hibernate as a persistence provider and creates a Flight entity, which
has FlightKey as its composite primary key class. Additionally, the script adds fields to the
Flight and FlightKey classes. If you are using a different database than MySQL or your
connection settings are different than what is specified in the script, then modify the script

To view dynamic finder methods, follow the given steps:

1. Start Roo shell and set the focus of the subsequent commands on the Flight entity using the focus
roo> focus --class ~.domain.Flight

2. Execute the finder list command to view the list of candidate dynamic finder
methods for the Flight entity, as shown here:
~.domain.Flight roo> finder list
findFlightsByCreatedDateBetween(Date minCreatedDate, Date
findFlightsByCreatedDateGreaterThan(Date createdDate)

To add dynamic finder methods, follow the given steps:

1. Add the findFlightsByDestinationLikeAndOriginLike dynamic finder
method to the Flight entity using the finder add command:

.. roo> finder add findFlightsByDestinationLikeAndOriginLike
Updated SRC_MAIN_JAVA\sample\roo\flightapp\domain\
Created SRC_MAIN_JAVA\sample\roo\flightapp\domain\Flight_Roo_Finder.aj

The following code shows the auto-generated implementation of the
findFlightsByDestinationLikeAndOriginLike finder method in the Flight_Roo_Finder.aj file:

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
public static TypedQuery
Flight.findFlightsByDestinationLikeAndOriginLike(String destination, String origin) {
  if (destination == null || destination.length() == 0)
     throw new IllegalArgumentException("The destination argument is required");
  if (origin == null || origin.length() == 0)
     throw new IllegalArgumentException("The origin argument is required");
  EntityManager em = Flight.entityManager();
  TypedQuery q = em.createQuery("SELECT Flight FROM Flight AS flight WHERE            
                    LOWER(flight.destination) LIKE
                    LOWER(:destination) AND LOWER(flight.origin) LIKE
                    LOWER(:origin)", Flight.class);
   q.setParameter("destination", destination);
   q.setParameter("origin", origin);
   return q;