[英]how to pass Map or List<Object> as a parameter to JPA query
I need to pass a map as input parameter of type <Sting,String> or List into two JPA columns and get the result as List of records for all the entries in the map/list.我需要将 map 作为 <Sting,String> 或 List 类型的输入参数传递到两个 JPA 列中,并将结果作为映射/列表中所有条目的记录列表。
Something like this:是这样的:
@Query(
value =
"SELECT e from #{#entityName} e where e.name = KEY(someMap) and e.relationName = VALUE(someMap)")
List<Member> findByNameAndRelationNameIn(
@Param("someMap") Map<String, String> someMap);
OR或者
@Query(
value =
"SELECT e from #{#entityName} e where e.name IN (:#{#dataSpaceMembers.?[name]}) and e.dataSpaceName IN (:#{#dataSpaceMembers.?[dataSpaceName]})")
List<DataSpaceMember> findByNameAndDataSpaceIn(
@Param("dataSpaceMembers") List<DataSpaceMember> dataSpaceMembers);
But the application doesn't run since this is not a valid jpa query.但是应用程序不会运行,因为这不是有效的 jpa 查询。 I don't want to run single queries in loop, but looking for a single query which can give result as a list.
我不想在循环中运行单个查询,而是寻找一个可以将结果作为列表给出的查询。
I don't think this is possible using @Query notation, however, like Chris said in the comments, you can pretty quickly write some code to dynamically create this kind of statement using a criteria query.我认为使用 @Query 符号不可能做到这一点,但是,就像 Chris 在评论中所说的那样,您可以非常快速地编写一些代码来使用条件查询动态创建这种语句。
I think the code you're looking for would be something like this, where the supplied Map is a set of key/value pairs with the key being name
and the value being relationName
.我认为您正在寻找的代码应该是这样的,其中提供的 Map 是一组键/值对,键为
name
,值为relationName
。
EntityManager em;
public List<Member> get(Map<String, String> map) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Member> cq = cb.createQuery(Member.class);
Root<Member> root = cq.from(Member.class);
List<Predicate> predicates = new ArrayList<>();
for (Map.Entry<String, String> e : map.entrySet()) {
Predicate a = cb.equal(root.get("name"), e.getKey());
Predicate b = cb.equal(root.get("relationName"), e.getValue());
predicates.add(cb.and(a, b));
}
cq.where(cb.or(predicates.toArray(new Predicate[0])));
return em.createQuery(cq).getResultList();
}
Thr query this produces should have a combination of AND and OR statements that you're desiring, ie这个产生的查询应该有你想要的 AND 和 OR 语句的组合,即
SELECT * FROM member WHERE ((name = ? AND relationName = ?) OR (name = ? AND relationName = ?) ... etc)
Note:笔记:
Since a Map
can only contain a key once, you might consider using a List<KeyValue<String, String>>
or List<Pair<String, String>>
instead.由于
Map
只能包含一个键一次,您可以考虑使用List<KeyValue<String, String>>
或List<Pair<String, String>>
代替。 Both KeyValue and Pair can be found in Apache commons libraries and I believe Spring also includes a Pair implementation. KeyValue 和 Pair 都可以在 Apache 公共库中找到,我相信 Spring 也包含一个 Pair 实现。 Or you can write your own.
或者你可以自己写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.