从 JPQL
select p.name, d.street from Person p join Address d on d = p.address;
到标准
带有构造函数的选项:
首先在您的实体@OneToOne/@OneToMany 等中标记关系。使用@JoinColumn 即
public class Person {
private Integer id;
private String name;
@JoinColumn(name="id", referencedColumnName = "id")
private Address address;
}
稍后为您的结果类型创建一个类
public class Result(){
String name;
String street;
/* you must have constructor here for the multi select later */
public Result(String name,String street) {
this.name = name;
thi.street = street
}
}
然后做(em是实体经理)
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<PlaceSearch> query = cb.createQuery(PlaceSearch.class);
Root<Person> personRoot = query.from(Person .class);
Join<Person, Address> address= personRoot .join(Person_.address);
/ * without meta model
Join<Person, Address> address= personRoot .join(person.get("address"));
*/
/* we know Result has a construct of (String,String) . this is important for the multi select here */
query.multiselect(person.get(Person_.name),address.get(Address_.street);
List<Result> result = em.
createQuery(query).getResultList();