英文:
Create a Predicate to match an entity with an entry in a Map property
问题
我正在尝试创建一个 `javax.persistence.criteria.Predicate`,以便匹配在 `Map<String,String>` 属性中包含特定键/值条目的实体。这是在 Spring Data JPA 和 `JpaSpecificationExecutor<MyEntity>` 存储库的上下文中。
```java
class MyEntity {
@ElementCollection(fetch = FetchType.EAGER)
...
Map<String, String> metadata = new HashMap<>();
}
static Specification<MyEntity> hasMetadata(String name, String value) {
return (entity, criteriaQuery, criteriaBuilder) -> {
Path<Map<String,String>> metadata = entity.get("metadata");
// fixme: insert magic
//
// not quite right: cb.isMember(cb.literal(value), metadata)
return ...
};
}
这里有一个稍微相关的问题 https://stackoverflow.com/questions/13982058/criteriabuilder-and-ismember-of-list-on-entity-hibernate,但我从那里没有获取到太多信息。
一个解决方案会很好,还有一个指向详细说明的文档的指针也会很好。我的 Google 搜索能力不足以找到这方面的信息。
<details>
<summary>英文:</summary>
I'm trying to create a `javax.persistence.criteria.Predicate` to match entities which contain a certain key/value entry in a `Map<String,String>` property. This is in the context of Spring Data JPA and a `JpaSpecificationExecutor<MyEntity>` repository.
```java
class MyEntity {
@ElementCollection(fetch = FetchType.EAGER)
...
Map<String, String> metadata = new HashMap<>();
}
static Specification<MyEntity> hasMetadata(String name, String value) {
return (entity, criteriaQuery, criteriaBuilder) -> {
Path<Map<String,String>> metadata = entity.get("metadata");
// fixme: insert magic
//
// not quite right: cb.isMember(cb.literal(value), metadata)
return ...
};
}
There is a slightly related question https://stackoverflow.com/questions/13982058/criteriabuilder-and-ismember-of-list-on-entity-hibernate, but I haven't been able to glean much info from there.
A solution would be nice, but also a pointer to documentation where this is specified too. My Google-fu is failing me.
答案1
得分: 2
我在这里找到了一个非常相似的问题:https://stackoverflow.com/questions/5580614/jpa-criteriabuilder-join-maps,其中提供了一个看起来现在可以工作的解决方案:
static Specification<MyEntity> hasMetadata(String name, String value) {
return (entity, criteriaQuery, criteriaBuilder) -> {
MapJoin<MyEntity, String, String> join = entity.joinMap("metadata");
return criteriaBuilder.and(
criteriaBuilder.equal(join.key(), name),
criteriaBuilder.equal(join.value(), value)
);
};
}
英文:
I found an very similar question here https://stackoverflow.com/questions/5580614/jpa-criteriabuilder-join-maps, which offered up something that seems to work now
static Specification<MyEntity> hasMetadata(String name, String value) {
return (entity, criteriaQuery, criteriaBuilder) -> {
MapJoin<MyEntity, String, String> join = entity.joinMap("metadata");
return criteriaBuilder.and(
criteriaBuilder.equal(join.key(), name),
criteriaBuilder.equal(join.value(), value)
);
};
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论