【问题标题】:Hibernate Criteria restriction by objects that are instances of the restriction class作为限制类实例的对象的休眠条件限制
【发布时间】:2012-08-02 01:00:35
【问题描述】:

因此,如果我要为员工设置限制,我会说

Criteria crit = sess.createCriteria(Employee.class);

所以现在我想弄清楚是否有可能代替这样做:

List<String> employeeIds;

Criteria crit = sess.createCriteria(Employee.class);
crit.add(Restrictions.in("id", employeeIds));
crit.createAlias("car", "car");
return crit.list();

为此:

List<Employee> employees;

Criteria crit = sess.createCriteria(Employee.class);
crit.add(Restrictions.in("", employees));                //Doesn't work, but I think you get what I'm trying to do, query by objects themselves
crit.createAlias("car", "car");
return crit.list();

我正在尝试通过员工对象列表限制对员工的查询。稍后我与另一个表进行连接,因此通过我正在为其创建条件的类的特定实例列表进行限制是很有用的。

这将与此示例 SQL 相同

SELECT * FROM employees
    JOIN cars
        ON cars.ownerName like employees.name
    WHERE employees.id in
        (<list of employee ids goes here>);

【问题讨论】:

    标签: hibernate criteria


    【解决方案1】:

    我要做的唯一想法是实际获取要检查的 ID 列表。 Restrictions.in 意味着您指定一个属性,因此“”将不起作用。尽管这比您发布的代码要多得多,但我认为这是解决您发布的问题的方法:

    List<Employee> employees; // This has to be the list o employees
    List<Integer> ids = new ArrayList();
    Iterator it = employees.iterator();
    while(it.hasNext()){
    ids.add(((Employee)it.next()).getId());
    }
    Criteria crit = sess.createCriteria(Employee.class);
    crit.add(Restrictions.in("id", ids));
    crit.add(Restriction.eq("car","car"));
    

    我希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      你试过了吗?

           Criteria crit = sess.createCriteria(Employee.class, "employee");
           crit.add(Restrictions.in("employee", employees));
      

      【讨论】:

      • 这是我尝试的第一件事。它最终说出了“ Employee 类的未知财产雇员”之类的东西。所以它不能神奇地找出我对 id 感兴趣。到目前为止,这并不是真正的世界末日,它只是让我的一个便利包装类没有我想象的那么有用。
      • 我一直使用“id”属性,所以我自己从来没有遇到过你的确切问题。我很好奇它是否会起作用。谢谢你告诉我。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多