Criteria API:按类类型过滤 [英] Criteria API: filter by class type

查看:73
本文介绍了Criteria API:按类类型过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是关系数据库的新手,我在创建查询方面遇到了一些问题。首先,我想尽快解释一下情况。我有几个实体类。所有这些都扩展 AbstractEntity EntityProperty 。因此实体可以拥有属性和属性拥有实体,因此存在双向关系。

现在让我们说 ConcreteEntity extends AbstractEntity 我想创建这样的查询:获取类型为 ConcreteEntity 的所有实体,其中至少包含在给定列表中包含名称的属性 propertyNames 。到目前为止,我有以下工作条件查询:

I'm relativley new to relational databases and I have some problems concerning the creation of queries. First I want to explain the situation shortly. I have several entity classes. All of them extend AbstractEntity or EntityProperty. So entities can have properties and properties have owning entities, so there is a bidirectional relation.
Now let's say ConcreteEntity extends AbstractEntity and I want to create queries like this: Get all entities of type ConcreteEntity which has at least on property with a name contained in the given list propertyNames. Until now I have the following working criteria query:

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

但现在我只想要那些 ConcreteEntity 。我怎么能实现这个目标?
在JPQL中我写了SELECT entity FROM EntityProperty property JOIN property.owningEntities entity,在这里我也不知道如何以只返回特定类型的方式编写它...

But now I want only those entities of type ConcreteEntity. How could I achieve this? In JPQL I wrote "SELECT entity FROM EntityProperty property JOIN property.owningEntities entity" and here I also have no idea how to write it in the way that only a specific type is returned...

提前感谢您的回答!

编辑:将第二个问题移至条件查询:隐隐绰绰的结果列表并在代码中删除不同(不起作用)

moved the second question to criteria query: indistinct result lists and removed distinct in the code (that didn't work)

推荐答案

我知道这是一个古老的问题,但万一有人偶然遇到同样的问题,以下是如何解决的问题。
您可以按照以下实体类型轻松过滤:

I know this is an old question but just in case someone stumbles upon the same problem, here is how it can be solved. You can easily filter by entity type like this:

Predicate p = cb.equal(entity.type(), cb.literal(ConcreteEntity.class));

其中实体可以是路径(包括根和连接), cb 是CriteriaBuilder对象。所以在你的情况下它会是这样的:

where entity can be a Path (Root and Join included), cb is a CriteriaBuilder object. So in your case it would be something like this:

CriteriaQuery<AbstractEntity> cq = cb.createQuery(AbstractEntity.class);
Root<EntityProperty> property = cq.from(EntityProperty.class);
Join<EntityProperty, AbstractEntity> entity = property.join(EntityProperty_.owningEntities);
cq.where(cb.and(
    property.get(EntityProperty_.name).in((Object[]) propertyNames),
    cb.equal(entity.type(), cb.literal.ConcreteEntity.class)
));
cq.select(entity);

这篇关于Criteria API:按类类型过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆