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