How hibernate works with HQL query if the Transformer is not explicit declared

冷暖自知 提交于 2019-12-03 22:58:30
Jitendra Vispute

When default Transformer used it expects the class to be hibernate entity meaning that it must be mapped with some table and in second case that is

Query query=session.createQuery(hql.toString()).setResultTransformer(Transformers.aliasToBean(B.class));

B is not hibernate entity( not mapped to any table its simple POJO without any hibernate specific annotations )

e.g 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 static 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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!