我目前正忙着使用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是一个空的List,尽管以下查询直接对数据库给出了结果:
Select myrelent.name from MYENTITY myent, MYRELATEDENTITY myrelent where myent.id = myrelent.myentity;
使用条件API构建的查询有什么问题?任何帮助表示赞赏!
答案 0 :(得分:0)
您无需指示CriteriaBuilder返回数组:无论如何它都会执行正确的工作。因此,只需将返回类型更改为String和select语句:
CriteriaQuery query = builder.createQuery(String.class);
Root<MyEntity> root = query.from(MyEntity.class);
query.select(root.get("myRelatedEntities").get("name"));
Query queryCriteria = em.createQuery(query);
List<String> resultRows = queryCriteria.getResultList();
无关:关于加入,进行加入的标准方法是:
Join<MyEntity, MyRelatedEntity> related = root.join("myRelatedEntities");
query.select(related.get("name"));
然而,知道你的方式完全有效是很好的!