2015-10-16 139 views
0

不幸的是,我不確切地知道如何解釋這個問題。我將如何使用jpa查詢jpa對象列表中的參數

我有兩個表只有鬆散的關係,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]

,但我需要做的工作分配的第二個查詢,我想只是傳遞的人的名單早在代替剝離出來的id 。所以像FROM Assignment a WHERE a.personId IN :persons.id.id AND a.active = true

這是可能與JPA查詢?

回答

0

似乎有點好奇,有一個@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() 

這工作,因爲你實際上是在PersonAssignment類別與@ManyToOne註釋之間建立鏈接。

編輯:看,你無法改變的模式我只是添加靜態幫手的人得到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() 
+0

我沒有這個選項。主鍵的定義與數據庫中的一樣。每當有人退出並被重新僱用時,他們都會使用具有不同日期的同一員工號碼。所以,如果我說只是'personId'是關鍵,我得到一個重複的關鍵錯誤 – mike

+0

好吧,想想你可能不幸運。我會發佈一個輔助函數... –