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.
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 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;
}}
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.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();
}
public class can not be static (invalid modifier)
ReplyDeleteYou are correct. Thanks for the note (I was probably copying the code of an inner class...).
ReplyDelete