2012-06-01 17 views
10

enter image description here¿Cómo hago con HQL, muchos para muchos?

Aquí está la estructura de mi base de datos. Relación de muchos a muchos. Quiero hacer una selección de autores que hayan escrito el mismo libro. Con SQL, lo hice. ¿Cómo lo hago con 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]); 
    } 

Respuesta

17

Suponiendo que los nombres de entidad son libro y el autor y el atributo que tiene autores del libro:

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

Steve Ebersole - muchas gracias !!! –

0

Tomemos las entidades Autores, Libros y AuthorBook.

Puede intentar la siguiente consulta.

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]); 
} 
Cuestiones relacionadas