How to join two unrelated entities using JPA and Hibernate

前端 未结 6 2169
天命终不由人
天命终不由人 2020-12-08 08:26

I have two tables - one containing Address and another containing Photographs. The only common field between them is the PersonID. These were mapped to two POJO Classes Add

6条回答
  •  旧时难觅i
    2020-12-08 09:17

    As I explained in this article, you have two options:

    1. Since Hibernate 5.1, you can use ad-hoc joins for unrelated entities.

      Tuple postViewCount = entityManager.createQuery(
          "select p as post, count(pv) as page_views " +
          "from Post p " +
          "left join PageView pv on p.slug = pv.slug " +
          "where p.title = :title " +
          "group by p", Tuple.class)
      .setParameter("title", "High-Performance Java Persistence")
      .getSingleResult();
      
    2. Prior to Hibernate 5.1, you could only use theta-style joins. However, a theta-style join is equivalent to an equijoin, hence you can only emulate INNER JOINs not OUTER JOINs.

      List postViewCount = entityManager.createQuery(
          "select p as post, count(pv) as page_views " +
          "from Post p, PageView pv " +
          "where p.title = :title and " +
          "      ( p.slug = pv.slug ) " +
          "group by p", Tuple.class)
      .setParameter("title", "Presentations")
      .getResultList();
      

    For more details, check out this article.

提交回复
热议问题