特定的SQL到JPQL查询转换

时间:2018-11-15 15:46:12

标签: jpa jpql

我正在寻找与JPQL中的此SQL查询等效的

SELECT l.*
FROM product_update l
    INNER JOIN (
        SELECT
            ID_PRODUCT,
            MAX(ID) AS maxID
        FROM product_update
        GROUP BY ID_PRODUCT
    ) groupel ON l.ID_PRODUCT = groupel.ID_PRODUCT
        AND l.ID = groupel.maxID
ORDER BY ID DESC 

我的java类

public class ProductUpdate extends BaseEntity {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "PRODUCT_UPDATE_SEQUENCE")
@Column(name = "ID")
private Long id;

@JoinColumn(name = "ID_PRODUCT")
@ManyToOne()
private Product product;


@JoinColumn(name = "ID_VERSION")
@ManyToOne()
private Versioning versioning;
}

的确,一个产品可能有多个版本,但是系统仅显示具有最大(id)的产品 示例:

1-Product 1 --- Version 1 
2-Product 2 --- Version 1
3-Product 3 --- Version 1
4-Product 1 --- Version 2
5-Product 3 --- Version 2
6-Product 3 --- Version 3

查询刚刚出来

2-Product 2 --- Version 1
4-Product 1 --- Version 2
6-Product 3 --- Version 3

谢谢。

1 个答案:

答案 0 :(得分:0)

我终于得到了很好的查询,

select pu from ProductUpdate pu where pu.id in (select MAX(pUd.id) from ProductUpdate pUd group by pUd.product.id) ORDER BY pu.id DESC. 

我只是使用帖子JPA CriteriaBuilder for join in subquery来回答我。

  1. 仅在WHERE中使用JPA子查询,因此使用Netbeans警告
  2. JPA中的
  3. INNER JOIN不接受子查询。