如何在Hibernate中向数据传输类添加集合

时间:2011-11-02 09:39:50

标签: java hibernate orm

我有以下设置,其中一个类包含一个集合。在查询此类的实例时,我喜欢填充数据传输类而不是数据类。但是,Hibernate会生成错误的SQL查询。我错过了什么?

Hibernate映射:

<class name="Thread" table="tbl_threads" schema="dbo">
    <id name="Id" type="integer">
        <column name="i_id"/>
        <generator class="identity"/>
    </id>
    <set name="keywords" inverse="true" lazy="false" cascade="all-delete-orphan" optimistic-lock="false">
        <key>
            <column name="thread_id" not-null="true"/>
        </key>
        <one-to-many class="Comment"/>
    </set>
<!-- ... -->
</class>

<class name="ThreadKeyword" table="tbl_keywords" schema="dbo">
    <composite-id name="id" 
        class="se.ericsson.eab.sdk.fido.server.api.pojos.report.ReportThreadKeywordId">
        <key-property name="keywordId" type="integer">
            <column name="keyword_id" />
        </key-property>
        <key-property name="threadId" type="integer">
            <column name="thread_id" />
        </key-property>
    </composite-id>
<!-- ... -->
</class>   

我正在使用的HQL是

SELECT new Composite(t.id, t.keywords, ...) 
  FROM Thread t, ThreadKeyword tk 
  WHERE t.id = tk.id.threadId

这将生成一个SQL,其中SELECT部分​​仅包含关键字属性的点:

select  thread1_.report_id as col_0_0_, . as col_92_0_ 
  from dbo.tbl_thread reportthre0_ inner join 
  dbo.tbl_keywords keywords4_ on reportthre0_.i_id=keywords4_.thread_id 

当我直接查询数据类时,它工作正常,即

SELECT t 
  FROM Thread t, ThreadKeyword tk 
  WHERE t.id = tk.id.threadId

据我所知,Hibernate会在线程表中找不到关键字的列名。这是对的,因为它是一个集合。它需要使用后续查询填充。如果我在Composite类的构造函数中省略了关键字,则查询会正确,但Hibernate不会填充Set。

如何填充关键字?

1 个答案:

答案 0 :(得分:0)

你不能用集合做到这一点。

t.id 是列/值

所以Hibernate将其转换为 thread1_.report_id为col_0_0 _ 。 Hibernate甚至给它别名 col_0_0 _

t.keywords 是一组值,因此Hibernate无法将集合转换为列/值。

  

查询包括要包含在最终结果中的列的列表   紧跟SELECT关键字 - 维基百科

现在

SELECT t  FROM Thread t, ThreadKeyword tk  WHERE t.id = tk.id.threadId

工作正常,因为Hibernate知道如何将你在那里的查询翻译成SQL。