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

流过昼夜 提交于 2019-12-23 20:34:16

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/4630445/hibernate-doesnt-support-accessing-fields-on-usertypes-for-projection-criterias

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