How hibernate works with HQL query if the Transfor

2019-04-02 13:26发布

问题:

I don't know where I can find the implementation mechanism of hibernate. I have a lot of questions about hibernate but we can start them from this one:

If there is a HQL like this:

from B b
where b.x =: x
and b.y =: y

And query code like this:

Query query = session.createQuery(hql.toString());

What is the default transformer to set all of the fields into B? I found this even doesn't need setter or getter to set values.

Or say, what is the differece between it and this one:

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

Thank you for reading this and any ideas are welcome.

回答1:

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.