簡體   English   中英

如何在JPA標准中使用投影和where子句?

[英]How to use projection and where clause in JPA criteria?

我有實體人

@Entity(name = "Person")
public class Person {

    @Id
    @GeneratedValue
    private Long id;
    private String name;
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "person")
    private Set<Phone> phones=new HashSet<Phone>();

    public Person() {
    }

    public Person(String name) {
        this.name = name;

    }

廣告實體電話:

@Entity(name = "Phone")
public class Phone {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "`number`")
    private String number;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "person_id", nullable = false)
    private Person person;

    public Phone() {
    }

他們有一對多的關系。 現在,我想在jpa標准中建立這樣的查詢:

select p.phones from person p join phone ph where p.name = :name;

因此,我想從人員名稱為參數的人員實體中提取Set<Phone> phones

我已經編寫了這個jpa條件查詢:

CriteriaBuilder builder = session.getCriteriaBuilder();
        CriteriaQuery<Person> query = builder.createQuery(Person.class);
        Root<Person> root = query.from(Person.class);
        CriteriaQuery<Person> where = query.where(builder.equal(root.get("name"), "Mary Dick"));
        CompoundSelection<Set> projection = builder.construct(Set.class, root.get("phones"));
        where.select(projection); //compile error: The method select(Selection<? extends Person>) in the type CriteriaQuery<Person> is not applicable for the arguments (CompoundSelection<Set>)
    }

但是它會產生編譯錯誤:

The method select(Selection<? extends Person>) in the type CriteriaQuery<Person> is not applicable for the arguments (CompoundSelection<Set>)

正確嗎? 我需要元模型類嗎?

CompoundSelection<Y> construct(Class<Y> result, Selection<?>... terms)

僅當查詢涉及某些未完全由單個實體類封裝的投影時,此方法才有用。 在這種情況下,第一個參數將是自定義POJO類(具有適當的構造函數),該類具有與查詢的select子句相對應的字段。

在這種情況下,選擇已經是實體類的一部分。 因此,您只需選擇所需的字段即可。

 CriteriaQuery<Person> query = builder.createQuery(Person.class);
 Root<Person> root = query.from(Person.class);
 query.where(builder.equal(root.get("name"), "Mary Dick"));
 query.select(root.get("phones"));

上面的查詢將返回人員列表。 但是,如果您僅查找可迭代的電話列表,請嘗試使用稍有不同的查詢。

select ph from phone ph join ph.person p where p.name = :name;

及其等效的CriteriaQuery:

CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Phone> query = builder.createQuery(Phone.class);
Root<Phone> root = query.from(Phone.class);
Join<Phone, Person> join = root.join(root.get("person"))            
query.where(builder.equal(join.get("name"), "Mary Dick"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM