【问题标题】:Hibernate and Unexpected end of Subtree exception休眠和子树异常的意外结束
【发布时间】:2011-01-05 04:47:29
【问题描述】:

我是 Hibernate 的新手。

我有一个Item POJO,其中包含一个由标签组成的Set<String>。标签包含在 Item 表中的另一个数据库表中,因此我进行了联接以填充 pojo。

我正在尝试从“Java Persistance with Hibernate”一书中运行一个简单的示例查询,我在其中查询from Item item where 'hello' member of item.labels。只是,由于某种原因,我得到了一个

 `org.hibernate.hql.ast.QuerySyntaxException: unexpected end of subtree[from /*qualified class path*/.Item item where 'hello' member of item.labels]`

可能导致此问题的原因是什么?

这是我的 POJO:

public class Item
       private int uuid;
       private Set<String>labels = new HashSet<String>();

       @Id
       public int getUuid(){
          return uuid; 
       }

       @CollectionOfElements
       @JoinTable(name="labels", joinColumns=@JoinColumn(name="uuid"))
       @Column(name="label")
       public Set<String> getLabels(){
            return labels;
       }
 }

【问题讨论】:

    标签: java hibernate hql


    【解决方案1】:

    通过谷歌搜索,您的参数集合似乎是空的。在调用查询之前,我会添加一个空检查。

    教训是 Google 是您的朋友。如果您无法找出错误消息,请尝试将其输入 Google(或您最喜欢的引擎)。您不太可能是第一个被它弄糊涂的人。

    【讨论】:

    • 然而,查询“from Item item”返回完全正确的非空集合。另外,查询“from Item item where size(item.labels)>0”返回正确,所以我认为这不是尺寸问题
    • ...如果集合只有一个元素,您会收到类似ERROR [main] o.h.h.PARSER // - &lt;AST&gt;:0:0: unexpected end of subtree 的日志消息。我喜欢这种诊断的有用性。
    【解决方案2】:

    对于原始集合,您应该像这样使用 HQL 查询:

    from Item item join item.labels lbls where 'hello' in (lbls)
    

    PS:'join' 是必需的,因为 'labels' 是 OneToMany 或 ManyToMany 变体,括号是必需的,因为 'lbls' 是一个集合

    【讨论】:

      【解决方案3】:

      HQL 中的 command 成员保留给非原始对象使用。你可以做两件事。您可以按如下方式创建SQLQuery

      SQLQuery sQuery = session.createSQLQuery("select * 
                                                from item_table it 
                                                inner join label_table lt 
                                                where it.id = lt.item_id 
                                                and lt.label = 'hello'");
      sQuery.list();
      

      或者您可以创建一个名为 Label 的类并在您的 HQL 中执行以下操作:

      from Item item, Label label
      where label member of item.labels
            and label.label = 'hello'
      

      希望这会有所帮助:)

      【讨论】:

      • createSQLQuery 现在已弃用并由 createNativeQuery 取代
      【解决方案4】:

      基于错误 HHH-5209 上的 cmets,这与类似的 JPQL 查询引发的异常大致相同,我相信这里的正确形式是:

      select item from Item item where 'hello' in elements(item.labels)
      

      elements 函数是关键。这可能比 Yuri 的建议稍微简单一些,因为它避免了显式连接。

      【讨论】:

        猜你喜欢
        • 2013-10-23
        • 2011-06-03
        • 2015-01-08
        • 1970-01-01
        • 2015-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-21
        相关资源
        最近更新 更多