【问题标题】:Retrieve many-to-many set and property via HQL通过 HQL 检索多对多集合和属性
【发布时间】:2012-03-13 01:37:44
【问题描述】:

我有这样的课程:

class EntryDB {
     @Id @GeneratedValue
     int id;
     @ManyToMany(cascade = CascadeType.ALL)
     List<Category> cats;
}


class Category {
     @Id @GeneratedValue
     int id;
     String name;
}

所以每个条目可以属于零个或多个类别。它工作正常。但我需要检索格式为 entry_id->(cat_id, cat_id, cat_id)

的条目列表

我在努力

select id, cats from EntryDB

但它不起作用,我看到异常如下:

调试输出:休眠:选择 entrydb0_.id 作为 col_0_0_,{non-qualified-property-ref} 作为 col_1_0_,category2_.id 作为 id1_,category2_.name 作为 name1_ from my_entry_table entrydb0_ 内部连接 ​​entrydb_category categories1_ on entrydb0_.id= categories1_.id 内连接 category2_ on categories1_.id=category2_.id

org.hibernate.exception.SQLGrammarException: could not execute query
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL serve...near 'as col_1_0_, category2_.id as id1_, category2_.name as name1_ from my_entry_table' at line 1

但是 HQL 喜欢

"select cats from EntryDB"

工作正常。但我需要知道条目的 id。

只是为了使用

session.load(EntryDB.class, id).getCats();

不是一个选项,因为“真正的”EntryDB 非常重,我只想知道“wich 条目属于 wich 类别”。如果我可以直接访问连接表,那将非常简单,但在 HQL 中无法完成。

您可能知道一些解决方法,但使用 JDBC 查询连接表。

【问题讨论】:

    标签: java hibernate many-to-many hql


    【解决方案1】:
    select entry.id, category.id from EntryDB entry 
    left join entry.cats category
    
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多