【问题标题】:Learning Criteria instead of hql, how to query using criteria manytomany with List of objects?学习标准而不是 hql,如何使用具有对象列表的标准多态查询?
【发布时间】: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


【解决方案1】:

请尝试:

我可以建议 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();

【讨论】:

    猜你喜欢
    • 2012-05-23
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多