Criteria Query:如何对Map集合中的值进行排序?
我似乎找不到如何执行此操作的示例,因此我们将不胜感激。
我的架构有一个如下所示的对象:
@Entity
public class User implements Serializable {
@Id private Integer id;
private String handle;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
@MapKey(name = "udkey")
private Map<String, UserData> attrs;
// rest of stuff omitted
}
引用的实体为:
@Entity
public class UserData implements Serializable {
@Id private Integer id;
private String udKey;
private String udData;
// rest of stuff omitted
}
因此,映射具有与给定用户关联的可变数量的数据属性,例如:(
udKey udData
"email" "[email protected]"
"realname" "john public"
"dob" "1960/01/30"
对于我实际上使用枚举对象的键,但我试图简化这个例子。)
问题是如何在标准查询中根据(例如)电子邮件地址对用户表进行排序?我想我是这样开始的:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<User> query = builder.createQuery(User.class);
Root<User> root = query.from(User.class);
MapJoin<User, String, UserData> join = root.join(User_.attrs);
Expression exp = // what goes here?
query.orderBy(builder.asc(exp));
我希望这已经足够清楚了。我想一般问题是如何使用文字键(示例中的“电子邮件”)构建进入地图的路径。再次感谢您的帮助。
I can't seem to find an example of how to do this, so any help will be appreciated.
My schema has an object that looks like this:
@Entity
public class User implements Serializable {
@Id private Integer id;
private String handle;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
@MapKey(name = "udkey")
private Map<String, UserData> attrs;
// rest of stuff omitted
}
and the referenced entity as:
@Entity
public class UserData implements Serializable {
@Id private Integer id;
private String udKey;
private String udData;
// rest of stuff omitted
}
So the map has a variable amount of data attributes associated with a given user, for example:
udKey udData
"email" "[email protected]"
"realname" "john public"
"dob" "1960/01/30"
(for the keys I actually use enum objects, but I am trying to simplify this example.)
The question is how do I sort the User table on (for example) the e-mail address in a Criteria Query? I think I start as follows:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<User> query = builder.createQuery(User.class);
Root<User> root = query.from(User.class);
MapJoin<User, String, UserData> join = root.join(User_.attrs);
Expression exp = // what goes here?
query.orderBy(builder.asc(exp));
I hope this is clear enough. I guess the generic question is how do I construct a path into the map with a literal key ("email" in the example). Again thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要按 udData 进行排序,但由于它是 OneToMany,因此您需要在 where 子句中过滤掉电子邮件。如果某些用户没有电子邮件,您将需要外部加入。
如果您需要按多个键进行排序,那么您需要有多个联接。
You would need to order by the udData, but because it is a OneToMany you would need to filter out email in the where clause. If some user do not have an email, you would need to outer join.
If you need to order by multiple of the keys, then you need to have multiple joins.