我有这个实体,想找到任何具有相同属性集的实体。
@Entity
public class PropertyResource {
@ElementCollection
@MapKeyColumn(name = "property_key")
@Column(name = "property_value")
@CollectionTable(name = "resource_properties")
private Map<String, String> properties = Maps.newHashMap();
...
}
这是我使用标准构建器的实现:
public List<PropertyResource> findDuplicateProperties(PropertyResource resource) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<PropertyResource> query = builder.createQuery(PropertyResource.class);
Root<PropertyResource> resourceRoot = query.from(PropertyResource.class);
List<Predicate> clauses = Lists.newArrayList();
for (Entry<String, String> entry : resource.getProperties().entrySet()) {
MapJoin<PropertyResource, String, String> properties = resourceRoot.joinMap("properties", JoinType.INNER);
clauses.add(builder.and(builder.equal(properties.key(), entry.getKey()), builder.equal(properties.value(), entry.getValue())));
}
if (!resource.isNew()) {
clauses.add(builder.notEqual(resourceRoot.get("id"), resource.getID()));
}
clauses.add(builder.equal(resourceRoot.get("type"), resource.getType()));
return em.createQuery(query.where(clauses.toArray(new Predicate[clauses.size()]))).getResultList();
}
我正在为每个属性做一个额外的加入。相同类型的属性和资源具有相同的属性键的数量并不多。这在 h2 中效果很好,它产生了这个:
select ...
from resource_table propertyre0_
inner join resource_properties properties1_ on propertyre0_.entid=properties1_.PropertyResource_entid
inner join resource_properties properties2_ on propertyre0_.entid=properties2_.PropertyResource_entid
where properties1_.property_key=? and properties1_.property_value=?
and properties2_.property_key=? and properties2_.property_value=?
and propertyre0_.entid<>4 and propertyre0_.resource_type=?
但是对于 Oracle,我得到了这个:
select ...
from resource_table propertyre0_
where propertyre0_.entid<>230 and propertyre0_.resource_type=?
我的查询有什么问题吗?
OBS:差点忘了。Hibernate 版本是 4.1.9.Final。