开发者

Hibernate sort by properties of inner bean?

开发者 https://www.devze.com 2022-12-14 03:57 出处:网络
In my domain model I have following Classes.A \'UserProfile\' has one \'SecurityPrincipal\' class SecurityPrincipal{

In my domain model I have following Classes.A 'UserProfile' has one 'SecurityPrincipal'

class SecurityPrincipal{
 private String loginId;
 private String password;
 private Date registeredData;
 private int status;
}



class UserProfile {

private String name;
private String company;
private SecurityPrincipa principal

}

I want to get the sorted results of 'UserProfile' objects and it works fine for simple properties.Like

DetachedCriteria criteria=DetachedCriteria.forClass(UserProfile.class);     

criteria.addOrder(Order.asc("name");

But when I try to access properties of inner bean (SecurityPrincipal instance) like

criteria.addOrder(Order.asc("principal.status");

Hibernate gives the error:

Caused by: org.hibernate.QueryException: could not resolve property: securityPrincipal.status of: com.bigg.ibmd.usermanagement.model.UserProfile at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:44) at org.hibernate.persister.entity.AbstractPropertyMapping.toColumns(AbstractPropertyMapping.java:59) at org.hibernate.persister.entity.BasicEntit开发者_StackOverflow中文版yPropertyMapping.toColumns(BasicEntityPropertyMapping.java:31)

How can I sort my results by properties-of-a-property?

Thanks


Try this:

DetachedCriteria criteria=DetachedCriteria.forClass(UserProfile.class);         
criteria.createAlias("principal", "p");
criteria.addOrder(Order.asc("p.name"));

I haven't tried it, nor am I sure that it's the nicest way, but I think it should work.


For filtering by multiple fields you ought to use @OrderBy annotation. For example:

@OrderBy("id, name, whatever") private SecurityPrincipa principal ...

Pay attention JPA Criteria api 2.0 generates OUTER JOIN for collections. It means if you have not One to One but One to Many relation in the table it fetchs multiple results:

@OrderBy("weight, height") private Collection userVitalStatsCollection;

To avoid duplicates it is handy to use Database View.

0

精彩评论

暂无评论...
验证码 换一张
取 消