简体   繁体   English

使用Hibernate 3查询多对一属性

[英]Query on many-to-one property with Hibernate 3

Java / Hibernate-3. Java / Hibernate-3。 I have an object called "Ticket", and it has a many-to-one association to "Person". 我有一个名为“ Ticket”的对象,它与“ Person”具有多对一关联。 This is mapped as: 映射为:

<class name="Ticket"> 
   ...
   <many-to-one name="person" class="Person" ...>
   ...
</class>

I want to query for Tickets, and limit my results by a property on Person. 我想查询票证,并通过Person上的一个属性来限制我的结果。 I'd like to list all Tickets which have assigned_to = 'ADMIN' or person.role = 'ADMIN' . 我想列出所有具有assigned_to = 'ADMIN' or person.role = 'ADMIN' I was expecting to be able to do something like this: 我期望能够做这样的事情:

        query.add(
            Expression.or(
                Expression.eq("assigned_to", "ADMIN"),
                Expression.eq("person.role", "ADMIN")
            )
        );

But I get an error: could not resolve property: person.role of: model.Ticket 但是我收到一个错误: could not resolve property: person.role of: model.Ticket

How can I query for Ticket , restricting results based on Ticket.Person.role ? 如何查询Ticket ,限制基于Ticket.Person.role结果?

You need to create an Alias for the second table first: 您需要首先为第二个表创建别名:

List tickets = sess.createCriteria(Ticket.class)
    .createAlias("person", "p")
    .add( Restrictions.eqProperty("p.role", "ADMIN") )
    .list();

By setting the alias you can refer to the second table. 通过设置别名,您可以参考第二张表。 If you don't explicitly set the alias, Hibernate will create its own alias. 如果您未明确设置别名,则Hibernate将创建自己的别名。 And you eq("person.role", "ADMIN") isn't using that alias correctly, so you have an invalid query. 而且您eq(“ person.role”,“ ADMIN”)没有正确使用该别名,因此查询无效。 By explicitly setting the alias yourself, you know the alias and can refer to it correctly. 通过自己显式设置别名,您将知道别名并可以正确引用它。

You can do it easily enough using the criteria API, as in 15.4. 您可以使用条件API轻松完成此操作,如15.4所示。 Criteria Queries - Associations of the Hibernate 3.2 manual. Criteria Queries- Hibernate 3.2手册的关联 The key point is that you need to define another criteria for the Ticket->Person association, and then apply the filter to that. 关键点是,您需要为Ticket-> Person关联定义另一个条件,然后对其应用过滤器。 Alternatively, define an alias, as per that link. 或者,根据该链接定义别名。

It's hard to give you a code sample, since your original sample is so brief there's not much context. 很难给您一个代码示例,因为您的原始示例非常简短,因此上下文不多。

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

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