Wednesday, January 20, 2010

Using Hibernate Transformers

There are times we have a class, we would like to fill with data according the data returned from a query. The class is a simple POJO and not an Hibernate entity, so Hibernate won’t recognize this class.
This can be done in Hibernate by using Transformers. Let’s have a look on a simple example, showing how Transformers can be used. First, let’s have a look at a simple POJO class named: “UserActivityStat”.
This class contains some statistical information. We would like to fill the statistical information of an instance, directly from running an Hibernate HQL.
public class UserActivityStat
{
private int totalPhotos;
private int totalViews;

public UserActivityStat() {
}

public int getTotalPhotos() {
return totalPhotos;
}

public void setTotalPhotos(int totalPhotos) {
this.totalPhotos = totalPhotos;
}

public int getTotalViews() {
return totalViews;
}

public void setTotalViews(int totalViews) {
this.totalViews = totalViews;
}
}
Now, let’s have a look at a simple method, that uses hibernate HQL and the Transformers class to fill “UserActivityStat” instance with data:
public UserActivityStat getUserActivityStat(User user)
{
return (UserActivityStat)hibernateSession.createQuery("select count(*) as totalPhotos, sum(p.views) as totalViews " +
"from Photo p where p.user = :user " +
"p.dateCreated  <= :now").
setParameter("user", user).
setTimestamp("now", new Date()).
setResultTransformer(Transformers.aliasToBean(UserActivityStat.class)).uniqueResult();
}
Note, that each of the 2 columns has an alias. This alias must be the name of the property on the “UserActivityStat” class. Also note for the use of the “setResultTransformer” along the “Transformers” class.

2 comments:

  1. public class can not be static (invalid modifier)

    ReplyDelete
  2. You are correct. Thanks for the note (I was probably copying the code of an inner class...).

    ReplyDelete