I’ve used Hibernate in the past with EJB3 annotations. Frequently I needed to map query results that didn’t correspond to Entity objects to value objects that could then be passed to the business or view tier. This is fairly trivial using the Hibernate Query API’s:


 public List<CustomerCityInfo> getCustomerCityInfo()
 {
     Query query = this.sessionFactory.getCurrentSession().createQuery("SELECT c.name, c.address.city from Customer c");
     query.setResultTransformer(Transformers.aliasToBean(CustomerCityInfo.class));
     return query.list();
 }

I ran into this need again when I started using JPA with the Hibernate JPA provider. I didn’t want to write non-portable code so I didn’t want to have to access the underlying Hibernate Session object.

My first naive attempt looked something like this:


 public List<CustomerCityInfo> getCustomerCityInfo()
 {
     Query query = entityManager.createQuery("SELECT c.name, c.address.city from Customer c");
     List<Object[]> resultList = query.getResultList();
     List<CustomerCityInfo> customerList = new ArrayList<CustomerCityInfo>();
     for (Object[] obj : resultList)
     {
         CustomerCityInfo customer = new CustomerCityInfo();
         customer.setName(obj[0]);
         customer.setCity(obj[1]);
         customerList.add(customer);
     }

     return customerList;
 }

Yuck!

I had some spare cycles recently so I did some google searching and discovered the “SELECT NEW” syntax that JPQL supports. This allows you to do something like this instead of the monstrosity above:


 public List<CustomerCityInfo> getCustomerCityInfo()
 {
     Query query = entityManager.createQuery("SELECT NEW com.mycompany.model.CustomerCityInfo(c.name, c.address.city) from Customer c");
     return query.getResultList();
 }

Much cleaner syntax. Much easier to maintain.

Cheers!

Advertisements