使用jpa条件API

时间:2018-01-03 16:04:22

标签: java jpql

我有两个实体Document和Property,其中一个文档具有一组属性:

@Entity 
public class Document{
 @Id
 private Integer id;

 @OneToMany
 private Set<Property> properties;
}

@Entity
public class Property{
 @Id
 private Integer    id;

 private String key;
 private String value;
}

我想使用Criteria API实现以下JPQL查询:

SELECT d FROM Document d 
    WHERE "value11" = ANY(SELECT p.value FROM d.properties p WHERE p.key="key11") 

我尝试了以下内容:

EntityManager em = PersistenceManager.INSTANCE.getEntityManager();

CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Document> query = criteriaBuilder.createQuery(Document.class);

Root<Document> fromDoc = query.from(Document.class);

Subquery<String> subQuery = query.subquery(String.class);

Root<Property> subRoot = subQuery.from(Property.class);

subQuery.select(subRoot.get(Property_.value));

SetJoin<Document, Property> join = fromDoc.join(Document_.properties, JoinType.INNER);

subQuery.select(join.<String> get("value"));
subQuery.where(criteriaBuilder.equal(join.<String> get("key"), "key11"));

query.where(criteriaBuilder.equal(criteriaBuilder.any(subQuery), "value11"));

Query q = em.createQuery(query);
List<Document> docs = q.getResultList();

PersistenceManager.INSTANCE.close();

但我得到了这个例外:

  

异常说明:查询尚未正确定义,   表达式构建器丢失。对于子和并行查询,请确保   查询构建器始终位于左侧。查询:   ReadAllQuery(referenceClass = Document)at   org.eclipse.persistence.exceptions.QueryException.invalidBuilderInQuery(QueryException.java:689)     在   org.eclipse.persistence.internal.expressions.SQLSelectStatement.appendFromClauseToWriter(SQLSelectStatement.java:537)     在   org.eclipse.persistence.internal.expressions.SQLSelectStatement.printSQL(SQLSelectStatement.java:1704)

任何帮助将不胜感激!

0 个答案:

没有答案