hibernatehibernate-criteriausertype

Hibernate doesn't support accessing fields on usertypes for projection criterias?


My Classes:

public class User 
{
   @Type(type="AccountType")
   private AccountType accountType;
}

public class AccountType 
{
   private String name;

   private AccountType(String name)
   {
      this.name = name;
   }

   public static AccountType User = new AccountType("User");
   public static AccountType Administrator = new AccountType("Administrator");
}

I also have a properly setup AccountTypeUserType.

My Query:

List results = session.createCriteria(User.class)
   .setProjection(Projections.projectionList()
      .add(Projections.property("accountType.name"), "accountType)
   )
   .setResultTransformer(Transformer.aliasToBean(UserSummary.class))
   .list()

The problem I run into is that my query fails with...

org.hibernate.QueryException: could not resolve property: accountType.name of: com.huskyenergy.routecommander.domain.rtc.User

Oh and you cannot .createAlias("accountType", "at") either because accountType is not an association.

Any thoughts?


Solution

  • As you probably realized, an UserType is not an entity. The best way to see why you can't access a property in an UserType is to use URL as the example. You won't do a query asking for URL.host, but for URL itself. That's why an UserType should know how to transform a String into an Object, and an Object into String, for instance. So, you'll have to use something like this:

    .add(Projections.property("accountType.name"), AccountType.User)
    

    Look at this UserType example and the test case for it from the test suite.

    But I think the real question is why you are not using an Enum (and @Enumerated), instead of this UserType. I think that an Enum is a better fit, as it's internally an UserType, but it's "native" to Hibernate.