当我传递一个整数(作为authorId)来查找与该作者相关联的书籍时,如何进行查询?我试过下面的一个给了我一个'不是一个关联ID'。这样做的正确方法是什么?
此外,这个多对多创建了第三个表格,该表格基于书籍中作者属性的注释。
实体
@Entity
class Book{
@Id
@GeneratedValue
private Integer id;
@ManyToMany(cascade = CascadeType.ALL)
@Column(name="Authors")
@JoinTable(name = "author_book", joinColumns =
{ @JoinColumn(name = "authors_id") },
inverseJoinColumns = { @JoinColumn(name = "books_id") })
private List<Author> authors;
//getters-setters
}
@Entity
class Author{
@Id
@GeneratedValue
private Integer id;
private String name;
@ManyToMany(mappedBy = "authors",cascade = CascadeType.ALL)
private List<Book> books;
//getters-setters
}
执行所需行为的功能
public List<Book> getBooksByAuthorId(int authorId) {
Session session = HibernateUtil.getSession();
Criteria cr = session.createCriteria(Book.class, "book");
cr.createAlias("book.authors", "authors");
cr.createAlias("authors.id", "authid");
cr.add(Restrictions.eq()) //edited after initial post this line should be removed
cr.add(Restrictions.eq("auth.id", authorId));
List<Book> results = cr.list();
session.close();
return results;
}
答案 0 :(得分:0)
请尝试:
我可以推荐JPA Criteria API(与Hibernate Criteria API不同) Hibernate Criteria API现在被视为已弃用。
通过提供作者ID获取与作者相关的书籍列表:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery();
Root book = cq.from(Book.class);
// // declaring parameter 'authorId'
cq.where(cb.equal(book.get("id"), cb.parameter(Integer.class, "authorId"));
Query query = em.createQuery(cq);
// supplying parameter 'authorId' to query
query.setParameter("authorId", id);
List<Author> authors = query.getResultList();