0

好吧,我有两张桌子:

产品_历史

product_id  last_update_date
-------------------------------
1           12JAN2012
1           13JAN2012
1           14JAN2012
2           13JAN2012
3           12JAN2012
4           12JAN2012

产品

product_id, product_name
-------------------------
1           Orange
2           Mango
3           Apple
4           Strawberry

产品 JPA 对象如下所示:

@Entity
@Indexed
@Table(name="Products")
public class Product extends AbstractDomainObject {

    private static final long serialVersionUID = 8619373591913330663L;

    private String product_id;
    private String product_name;

    @Id 
    @Column(name="product_id")
    public Long getProduct_id() {
        return product_id;
    }

    public void setProduct_id(String Product_id) {
        this.Product_id = Product_id;
    }
}

我需要编写一个 JPQL 查询,以便获得在两个日期之间更新的产品列表。在普通的 sql 中,我会做这样的事情:

-- assuming startDate is 13JAN2012 and endDate is 14JAN2012

Select product_name from products where product_id in 
(Select product_id where max(last_update_date) betwen startDate and endDate);

如何为 JPA 编写等效查询?我尝试过这样的事情,但没有运气。

String queryString = "from Products p, Product_History h where " +
                "product_id = :newId " +
                "and product_id in ( " +
                "Select product_id from product_history + +
                            "where max(last_update_date) between max:startDate and :endDate);

    Query query = entityManager.createQuery(queryString);   
    query.setParameter("newId", 1);
    query.setParameter("startDate", '13JAN2012');   
    query.setParameter("endDate", '14JAN2012'); 

    return query.getResultList();   
4

1 回答 1

3

您必须使用 @OneToMany 连接对 Product 中的 product_histroy 进行惰性获取,然后使用:

select distinct p from Products p 
where p.productHistory.lastUpdateDate > ? and p.productHistory.lastUpdate < ?
于 2012-06-09T19:58:02.953 回答