日期:2014-05-18  浏览次数:20649 次

Hibernarte many-to-many 查询问题
假设现在有两张表Book和Category(书的类型),通过一张中间表category_book实现many-to-many.  
   
  实体对象Book中有个Set保存Category,实体对象Category中也有一个Set保存Book。  
   
  当我要查询属于某个Category的所有Book时,HQL应该怎样写?????  
   
  查询某个Category中有多少本书时,HQL应该怎样写????  

这是我的hbm.xml的片断  
  Book.hbm.xml:  
  <set name="categorys" table="category_book" lazy="true" inverse="true" cascade="save-update">  
  <key column="bookId"></key>  
  <many-to-many class="Category" column="categoryId"></many-to-many></set>  
   
  Category.hbm.xml:  
  <set name="books" table="category_book" cascade="save-update" lazy="true" >  
  <key column="categoryId"></key>  
  <many-to-many class="Book" column="bookId"/>  
  </set>

------解决方案--------------------


Category c= get(Category.class,id);
Set s = c.getBooks();
------解决方案--------------------
select b.categorySet from Book b where b.id=?
Java code
List<Category> categorys= session.
        createQuery("select b.categorySet from  Book b where b.id=:id").setLong("id", bookId).list();
List<Book> books= session.
        createQuery("select c.bookSet from  Category c where c.id=:id").setLong("id", categoryId).list();

------解决方案--------------------
确认category里面有吗,检查一下你的控制台打出的sql语句,看看正确与否

如果都正确,看下系统是否报异常,把异常贴上来看看
------解决方案--------------------
查询属于某个Category的所有Book:
select book from Book book,Category category where category = all elements(book.categorys) and category.categoryId=?

查询某个Category中有多少本书
select count(*) from Book book,Category category where category = all elements(book.categorys) and category.categoryId=?

这其实用的是SQL的all函数。
关于elements在Hibernate reference 的 Hql 里有介绍。