Criteria Query: Fuzzy Result Lists

I have two problems. Let's say I have an entity class called MyEntity

. This class has two properties. Therefore, I have two different classes Property1

and Property2

, which are also entity classes. There is a bi-directional relationship betweens MyEntity

, and property classes especially Property1

have an attribute List<MyEntity> owningEntities

and Property2

have an attribute MyEntity owningEntity

. Now I have the following request:

SELECT e FROM Property1 p JOIN p.owningEntities e WHERE p.name IN :propertyNames  

      

This query returns all entities that have a property of the first type with at least one of the given names. But overall, the returned list is fuzzy. The problem is SELECT DISTINCT doesn't work here, at least with API criteria - I haven't tried this with jpql. The code for requesting criteria looks like this:

CriteriaQuery<MyEntity> cq = cb.createQuery(MyEntity.class);
Root<Property1> property = cq.from(Property1.class);
SetJoin<Property1, MyEntity> entity =
                property.join(Property1_.owningEntities);
cq.where(property.get(Property1_.name).in((Object[]) propertyNames));
cq.select(entity);
// cq.select(entity).distinct(true); --> runtime error
List<MyEntity> resultList = em.createQuery(cq).getResultList();

      

Is there a way to get a list of the resulting results? I can just convert the list to a set, but it seems inefficient to retrieve the same results multiple times.

The next problem is that of course I want all objects that have a property of any type with at least one of the given names. So far, I have two queries and then I combine the results. But again I am retrieving many results several times. So, is there a way to efficiently combine the following two queries?

SELECT e FROM Property1 p JOIN p.owningEntities e WHERE p.name IN :propertyNames  
SELECT e FROM Property2 p JOIN p.owningEntity e WHERE p.name IN :propertyNames  

      

Thanks in advance!

0


source to share





All Articles