我尝试使用JPA 2.0 Criteria API构建查询,基于这两个实体:
person(id, name)
address(person_id, house_no, street, city, country)
相应的实体是:
@Entity
@Table(name = "person")
public class Person {
@Id
private Integer id;
private String name;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id")
private Address address;
}
@Entity
@Table(name = "address")
public class Address {
@Id
@Column(name = "person_id")
private Integer personId;
@Column(name = "house_no")
private String houseNumber;
private String street;
private String city;
private String country;
}
现在,我想要获取所有人,我有一个类似的查询:
List<Person> getAll() {
CriteriaBuilder cb = manager.getCriteriaBuilder();
CriteriaQuery<Person> cq = cb.createQuery(Person.class);
Root<Person> root = cq.from(Person.class);
CriteriaQuery<Person> all = cq.select(root);
TypedQuery<Person> tq = manager.createQuery(all);
List<Person> res = tq.getResultList();
return res;
}
虽然这个查询有效,并且给了我所有拥有地址成员的人。我只想要城市和乡村的田地,我不想去找house_no和街道。
SQl查询将是:
select p.*, a.city, a.country from person as p left join address as a on p.id=a.person_id;
上述查询的JPQL可能类似于:
SELECT p, p.address.city, p.address.country FROM person p LEFT JOIN p.address address
但这似乎不起作用!!人实体持有地址,不能保留城市和国家属性。 我如何把正确的JPQL和相应的JPA 2.0标准查询?或者我是否必须更改我的实体结构?