0
好兩個表說我有兩個表:如何加入使用JPA的JPQL
Product_History
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();