如何使用HQL,多对多?

时间:2012-06-01 19:02:23

标签: hibernate

enter image description here

这是我的数据库结构。关系很多很多。我想选出一些写过同一本书的作者。使用SQL,我做到了。我如何使用HQL?

   Query query = session.createSQLQuery("SELECT FirstName, LastName FROM authors, books, author_book as ab WHERE ab.authorID=authors.authorID AND ab.bookID = books.bookID AND ab.bookID = :id");
   query.setInteger("id", 1);
   List list = query.list();
   Iterator<Object[]> iter = list.iterator();
   while (iter.hasNext()) {
       Object[] obj = iter.next();
       System.out.println(obj[0] + " " + obj[1]);
    }

2 个答案:

答案 0 :(得分:23)

假设实体名称是Book and Author,而Book具有authors属性:

select a.firstName, a.lastName from Book b join b.authors a where b.id = :id

答案 1 :(得分:0)

让我们采取实体作者,书籍和作者。

您可以尝试以下查询。

String hql = "select a.firstName, a.lastName from Authors a, Books b, AuthorBook ab where ab.authorId=a.authorId and ab.bookId=b.bookId and ab.bookId=:id";

List<Object[]> resultList = session.createQuery(hql).setInteger("id", 1).list();

for(Object[] result : resultList)
{

        System.out.println("First Name : " + result[0]);
        System.out.println("Last Name : " + result[1]);
}