问题
I have 2 little problems. Let's say I have an entity class called MyEntity
. This class has two kinds of properties. Therefore I have two different class Property1
and Property2
which are also entity classes. There are bidirectional relations betweens MyEntity
and the property classes, especially Property1
has an attribute List<MyEntity> owningEntities
and Property2
has the attribute MyEntity owningEntity
. Now I have the following query:
SELECT e FROM Property1 p JOIN p.owningEntities e WHERE p.name IN :propertyNames
This query returns all entities that has a property of the first type with at least one of the given names. But in general the returned list is indistinct. The problem is that the SELECT DISTINCT downs't work here, at least with criteria API - I didn't try it with jpql. The code for the criteria query looks as follows:
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 any way to get a distict result list? I can simply convert the list into a set, but it seems ineffective to extract the same results multiple times.
The next problem is, of course I want all entities that has a property of the any type with at least one of the given names. Until now I have two queries and afterwards I merge the results. But again I extract many results multiple times. So, is there any way to combine the following two queries in an effective way?
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!
来源:https://stackoverflow.com/questions/26237579/criteria-query-indistinct-result-lists