[英]How would I use jpa to query for a parameter IN a list of jpa objects
I don't know exactly how to phrase this question unfortunately. 不幸的是,我不知道该如何表达这个问题。
I have two tables that are only loosely related, PERSON and ASSIGNMENT. 我有两个只是松散相关的表,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;
}
The PERSON one is easy to get with FROM Person p WHERE [current date in between hire and termination]
可以很容易地
FROM Person p WHERE [current date in between hire and termination]
那里找到一个FROM Person p WHERE [current date in between hire and termination]
But i need to do a second query for assignments and I'd like to just pass the list of Persons back in instead of stripping out the id. 但是我需要对分配进行第二次查询,我只想将“人员”列表传递回去,而不是剥离ID。 So something like
FROM Assignment a WHERE a.personId IN :persons.id.id AND a.active = true
所以类似
FROM Assignment a WHERE a.personId IN :persons.id.id AND a.active = true
Is this possible with a JPA query? JPA查询可能吗?
It seems a little curious to have an @EmbeddedId
with date fields like that. 带有这样的日期字段的
@EmbeddedId
似乎@EmbeddedId
。 To be honest I'd lose the PersonPK
class and do something like this: 老实说,我会丢失
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;
}
Then you should be able to query by passing in the list of people: 然后,您应该可以通过传递人员列表进行查询:
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()
This works, because you are actually making a link between the Person
and Assignment
classes with the @ManyToOne
annotation. 之所以
@ManyToOne
,是因为您实际上是使用@ManyToOne
注释在Person
类和Assignment
类之间建立链接。
Edit: Seeing as you can't change the schema I'd just add a static helper to person to get the personNumbers for you: 编辑:看来您无法更改架构,我只是向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;
}
Then you can just call that when you need to set the params: 然后可以在需要设置参数时调用它:
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.