[英]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.