Jog*_*ogi 5 java sql jpql criteria-api jpa-2.0
我是关系数据库的新手,我在创建查询方面遇到了一些问题。首先,我想简短地解释一下情况。我有几个实体类。所有这些都扩展AbstractEntity或EntityProperty。所以实体可以有属性,属性也有拥有实体,所以存在双向关系。
现在让我们说ConcreteEntity扩展AbstractEntity,我想创建这样的查询:获取所有类型的实体,这些实体ConcreteEntity至少具有一个名称包含在给定列表中的属性propertyNames。到目前为止,我有以下工作条件查询:
CriteriaQuery<AbstractEntity> cq = cb.createQuery(AbstractEntity.class);
Root<EntityProperty> property = cq.from(EntityProperty.class);
Join<EntityProperty, AbstractEntity> entity = property.join(EntityProperty_.owningEntities);
cq.where(property.get(EntityProperty_.name).in((Object[]) propertyNames));
cq.select(entity);
Run Code Online (Sandbox Code Playgroud)
但现在我只想要那些类型为 的实体ConcreteEntity。我怎么能做到这一点?在 JPQL 中,我写了“SELECT entity FROM EntityProperty property JOIN property.owningEntities entity”,在这里我也不知道如何以仅返回特定类型的方式编写它...
感谢您提前回答!
编辑:将第二个问题移至标准查询:模糊结果列表并删除了代码中的不同(不起作用)
到目前为止我发现的唯一方法是创建一个枚举,其中每个类都有一个值生成的条件查询是
CriteriaQuery<AbstractEntity> cq = cb.createQuery(AbstractEntity.class);
Root<EntityProperty> property = cq.from(EntityProperty.class);
SetJoin<EntityProperty, AbstractEntity> entity =
property.join(EntityProperty_.owningEntities);
cq.where(property.get(EntityProperty_.name).in((Object[]) propertyNames),
entity.get(AbstractEntity_.entityType).in(suitableSubTypes));
cq.select(entity);
List<AbstractEntity> resultList = em.createQuery(cq).getResultList();
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,现在每个实体都有实体类型属性。我还必须每次创建合适的子类型集合。另一个问题是返回的类型是List<AbstractEntity>。我想要的是像这样的方法签名
public static <T extends AbstractEntity> List<T>
getEntities(Class<T> entityClass, String... propertyNames)
Run Code Online (Sandbox Code Playgroud)
但现在我有
public static List<AbstractEntity>
getEntities(Collection<AbstractEntityType> suitableSubTypes,
String... propertyNames)
Run Code Online (Sandbox Code Playgroud)
所以我还是希望有更好的解决方案......