getHibernateTemplate()。find()通过多对多关联

时间:2012-04-13 11:49:07

标签: spring hibernate

在以下场景中,多对多关联中,要传递给 getHibernateTemplate()。find()方法的正确查询是什么为了获得有参与者的事件的事件(和人)列表?

    _____________        __________________
   |             |      |                  |       _____________
   |   EVENTS    |      |   PERSON_EVENT   |      |             |
   |_____________|      |__________________|      |    PERSON   |
   |             |      |                  |      |_____________|
   | *EVENT_ID   | <--> | *EVENT_ID        |      |             |
   |  EVENT_DATE |      | *PERSON_ID       | <--> | *PERSON_ID  |
   |  TITLE      |      |__________________|      |  AGE        |
   |_____________|                                |  FIRSTNAME  |
                                                  |  LASTNAME   |
                                                  |_____________|



<class name="Event" table="EVENTS">
    <id name="id" column="EVENT_ID">
        <generator class="native"/>
    </id>   
    <property name="date" type="timestamp" column="EVENT_DATE"/>
    <property name="title"/>

    <set name="participants" table="PERSON_EVENT">
        <key column="EVENT_ID"/>
        <many-to-many column="PERSON_ID" class="Person"/>
    </set>      
</class>


<class name="Person" table="PERSON">
    <id name="id" column="PERSON_ID">
        <generator class="native"/>
    </id>
    <property name="age"/>
    <property name="firstname"/>
    <property name="lastname"/>

    <set name="events" table="PERSON_EVENT" inverse="true">
        <key column="PERSON_ID"/>
        <many-to-many column="EVENT_ID" class="Event"/>
    </set>

</class>

像这样的一些尝试失败,但有以下例外:

getHibernateTemplate().find("from Event event where event.participants != null");

org.springframework.dao.InvalidDataAccessResourceUsageException等等等 嵌套异常是org.hibernate.exception.SQLGrammarException:无法执行查询 等等

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用以下查询来获得相同的结果。

event.participants不为空的事件事件

答案 1 :(得分:0)

Ram Reddy建议查询有效,但我需要添加lazy =“false”:

<set name="participants" table="PERSON_EVENT" lazy="false">
        <key column="EVENT_ID"/>
        <many-to-many column="PERSON_ID" class="Person"/>
</set>