我目前正在努力使用 JPA Criteria API 创建查询。我想动态构建我的查询。使用元模型和类型化查询对我来说是没有选择的。假设我有以下实体:
@Entity
@Table(name = "MYENTITY")
public class MyEntity {
...
@OneToMany(mappedBy = "myEntity", fetch = FetchType.LAZY)
private Set<MyRelatedEntity> myRelatedEntities;
...
}
@Entity
@Table(name = "MYRELATEDENTITY")
public class MyRelatedEntity {
...
@ManyToOne
@JoinColumn(name = "MYENTITY", nullable = false)
private MyEntity myEntity;
...
}
我尝试通过加入“MyEntity”来查询“MyRelatedEntity”中的字段:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Object[]> query = builder.createQuery(Object[].class);
Root<MyEntity> root = query.from(MyEntity.class);
root.join("myRelatedEntities");
query.select(builder.array(root.get("myRelatedEntities").get("name")));
Query queryCriteria = em.createQuery(query);
List<Object[]> resultRows = queryCriteria.getResultList();
resultRows 是一个空列表,尽管直接在数据库上的以下查询给了我结果:
Select myrelent.name from MYENTITY myent, MYRELATEDENTITY myrelent where myent.id = myrelent.myentity;
使用条件 API 构建的查询有什么问题?任何帮助表示赞赏!