当前使用Eclipselink JPA 2.4.2,并通过@IdClass方法使用复合键将一堆对象存储在数据库中,即:
@Entity
@IdClass(ThingsPK.class)
public class MyBunchOfThings {
@Id
@GeneratedValue(generator="ID_SEQ")
@SequenceGenerator(name="ID_SEQ")
private Integer id;
@Id
private Date timestamp;
...
}
public class ThingsPK {
private Integer id;
private Date timestamp;
}
如果需要通过select in子句来选择其中一些内容,如何通过带有复合主键的JPQL来做到这一点?
例如
List<ThingsPK> keyList = ...
TypedQuery<MyBunchOfThings> query = em.createQuery("SELECT t FROM MyBunchOfThings t WHERE t.??? IN :keyList", MyBunchOfThings.class);
query.setParameter("keyList", keyList);
List<MyBunchOfThings> foundThings = query.getResultList();
最佳答案
如果要使用IN
JPQL运算符,请使用@EmbeddedId。否则,在查询中使用AND / OR,例如:
SELECT t FROM MyBunchOfThings t WHERE (t.id=:id1 AND t.timestamp=:ts1) OR (t.id=:id2 AND t.timestamp=:ts2) OR...
或者,您可以尝试以下查询:
List<ThingsPK> keyList = ...
TypedQuery<MyBunchOfThings> query = em.createQuery("SELECT t FROM MyBunchOfThings t WHERE t IN :keyList", MyBunchOfThings.class);