Question

I'm currently struggeling with creating queries by using the JPA Criteria API. I want to build my queries dynamically. Using a meta model and typed queries are no options for me. Assuming I have the following entities:

@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;
...
}

I try to to query fields from "MyRelatedEntity" by joining with "MyEntity":

    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 is an empty List, despite the following query directly on the database gives me results:

Select myrelent.name from MYENTITY myent, MYRELATEDENTITY myrelent where myent.id = myrelent.myentity;

What's wrong with my query built with the criteria API? Any help is appreciated!

Was it helpful?

Solution

You don't need to instruct CriteriaBuilder to return an Array: it will do the correct job anyway. So, simply change the return type to String and the select statement:

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();

Unrelated: regarding the join, the standard way to make a join is:

Join<MyEntity, MyRelatedEntity> related = root.join("myRelatedEntities");
query.select(related.get("name"));

However it's good to know that your way works altogether!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top