My favorites | Sign in
Project Logo
                
Search
for
Updated Nov 04, 2008 by piotr.bzdyl
Labels: Featured
Introduction  

ejb3criteria provides an API which is almost identical to Hibernate Criteria API but it doesn't use Hibernate at all. ejb3criteria allows for building a query in an object way instead of concatenating EJB Query Language fragments depending on search conditions.

Example

Assume we have a Customer class and we would like to search for persisted customer objects using different search criteria.

We could use EJB3 Query Language:

StringBuilder queryString = "SELECT c FROM Customer AS c WHERE ";
boolean addAndOperator = false;
if (searchOptions.getCustomerName() != null) {
    queryString.append("c.name ILIKE :customerName");
    addAndOperator = true;
}

if (searchOptions.getNumberOfEmployees() != null) {
    if (addAndOperator) {
        queryString.append(" AND ");
    }
    queryString.append("c.numberOfEmployees >= :noOfEmployees");
}

// more search options

Query query = entityMananger.createQuery(queryString.toString());

if (searchOptions.getCustomerName() != null) {
    query.setParameter("customerName", searchOptions.getCustomerName());
}

if (searchOptions.getNumberOfEmployees() != null {
    query.setParameter("noOfEmployees", searchOptions.getNumberOfEmployees());
}

// more parameter binding; yes, it could be handled using map, but what about temporal types?

List customers = query.getResultList();

Using ejb3criteria it is more object oriented and easier when it comes to providing values for query parameters as ejb3criteria does it automatically:

Criteria criteria = CriteriaFactory.createCriteria("Customer");

if (searchOptions.getCustomerName() != null) {
    criteria.add(Restrictions.ilike("name", searchOptions.getCustomerName());
}

if (searchOptions.getNumberOfEmployees() != null) {
   criteria.add(Restrictions.ge("numberOfEmployees", searchOptions.getNumberOfEmployees());
}

Query query = criteria.prepareQuery(entityManager);

List customers = query.getResultList();

How it works

ejb3criteria builds an object representation of a search query. Once it is complete and Criteria.prepareQuery(EntityMananger) is called, Criteria implementation does following:

  1. builds EJB3 query string
  2. calls entity manager to create Query object using query string generated in step #1
  3. binds all parameters on the Query object
  4. returns prepared query ready to execute it.


Sign in to add a comment
Hosted by Google Code