![](/img/trans.png)
[英]How can I sort a JPA query result where the parameter is a String and the result is a List of Objects?
[英]How would I use jpa to query for a parameter IN a list of jpa objects
不幸的是,我不知道该如何表达这个问题。
我有两个只是松散相关的表,PERSON和ASSIGNMENT。
public class Person {
@EmbeddedId
@Column
PersonPK id;
@Column
String otherStuff;
}
public class PersonPK {
@Column
long personNumber;
@Column
Date hireDate;
@Column
Date terminationDate;
}
public class Assignment {
@Id
@Column
long id;
@Column
long personId;
@Column
boolean active;
@Column
String otherStuff;
}
可以很容易地FROM Person p WHERE [current date in between hire and termination]
那里找到一个FROM Person p WHERE [current date in between hire and termination]
但是我需要对分配进行第二次查询,我只想将“人员”列表传递回去,而不是剥离ID。 所以类似FROM Assignment a WHERE a.personId IN :persons.id.id AND a.active = true
JPA查询可能吗?
带有这样的日期字段的@EmbeddedId
似乎@EmbeddedId
。 老实说,我会丢失PersonPK
类,并执行以下操作:
public class Person {
@Id
@Column
long personNumber;
@Column
Date hireDate;
@Column
Date terminationDate;
@Column
String otherStuff;
}
public class Assignment {
@Id
@Column
long id;
@ManyToOne
Person person;
@Column
boolean active;
@Column
String otherStuff;
}
然后,您应该可以通过传递人员列表进行查询:
List<Person> people = /* your list of people */
Query query = manager.createQuery("select a from Assignment a where a.person in :people");
query.setParameter("people", people);
List<Assigment> assignments = query.getResultList()
之所以@ManyToOne
,是因为您实际上是使用@ManyToOne
注释在Person
类和Assignment
类之间建立链接。
编辑:看来您无法更改架构,我只是向person添加一个静态助手来为您获取personNumbers:
public static List<Long> toPersonNumbers(List<Person> people) {
List<Long> numbers = new ArrayList<Long>();
for ( Person person: people ) {
numbers.add(person.id.personNumber);
}
return numbers;
}
然后可以在需要设置参数时调用它:
List<Person> people = /* your list of people */
Query query = manager.createQuery("select a from Assignment a where a.personId in :people");
query.setParameter("people", toPersonNumbers(people));
List<Assigment> assignments = query.getResultList()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.