【发布时间】:2017-12-13 10:38:06
【问题描述】:
当我传递一个整数作为 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;
}
【问题讨论】:
-
您能具体描述一下您在查询中要达到的目标吗?多对多关系应该通过中间表映射,所以你得到的行为是正确的。
-
如果我在这种情况下传递一个参数 int(authorid),或者更好的是一个字符串,我想返回与该作者关联的书籍列表。这样我就可以打印那些书单了。
-
请看下面的答案
-
抱歉回复晚了。错误在“book.authors”中。 .应该只是作者
标签: java hibernate jpa jakarta-ee hql