简体   繁体   English

使用hibernate Criteria返回set而不是list

[英]Return a set instead of list with hibernate Criteria

criteria = createCriteria("employee");  
criteria.add(Restrictions.eq("name", "John"));  
criteria.addOrder(Order.asc("city"));
criteria.addOrder(Order.asc("state"));
List result = criteria.list();

This statement returns a list of Employee objects. 此语句返回Employee对象的列表。 How can I make it return a Set of Employee objects instead, in order to remove duplicate data? 如何让它返回一Set Employee对象,以删除重复数据?

I understand I can achieve this by creating a set out of the returned list like below, but then I would lose the sorting order of the list. 我知道我可以通过创建一个返回列表的设置来实现这一点,如下所示,但后来我将失去列表的排序顺序。 And I don't want to have to write code to sort the set. 而且我不想编写代码来对集合进行排序。

Set<Employee> empSet = new HashSet<Employee>(result); 

I don't think it's possible to return a Set using Criteria based on the javadoc. 我不认为可以使用基于javadoc的Criteria返回Set However, if you want to remove duplicate data, why don't add a Projections.distinct(...) to your existing Criteria to remove the duplicates? 但是,如果要删除重复数据,为什么不在现有Criteria添加Projections.distinct(...)以删除重复项?

http://docs.jboss.org/hibernate/envers/3.6/javadocs/org/hibernate/criterion/Projections.html http://docs.jboss.org/hibernate/envers/3.6/javadocs/org/hibernate/criterion/Projections.html

UPDATE UPDATE

For example, if you want to apply a SELECT DISTINCT on the employee name (or some identifier(s)) to get a list of unique employees, you can do something like this:- 例如,如果要对员工姓名(或某些标识符)应用SELECT DISTINCT以获取唯一员工列表,则可以执行以下操作: -

List result = session.createCriteria("employee")
            .setProjection(Projections.distinct(Projections.property("name")))
            .add(Restrictions.eq("name", "John"))
            .addOrder(Order.asc("city"))
            .addOrder(Order.asc("state"))
            .list();

This way, you don't really need to worry about using Set at all. 这样,您根本不需要担心使用Set

As the comments and javadoc suggest, you have to return a List from Criteria . 正如评论和javadoc建议的那样,您必须从Criteria返回List Therefore, your only option is to remove uniques after the fact. 因此,您唯一的选择是在事后删除唯一身份。 As KepaniHaole said, you should use a LinkedHashSet if you want to preserve order. 正如KepaniHaole所说,如果你想保留订单,你应该使用LinkedHashSet

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM