在Criteria Queries中选择

时间:2012-08-24 17:59:18

标签: select jpa criteria multi-select

我有这个课程,例如:

public class Person {
    private Integer id;  
    private String name;  
    private Address address;  
}

public class Address {
    private Integer id;  
    private String street;  
    private String number;      

    ...
}

我想在JPA中为此SQL

构建CriteriaQuery
select p.name, d.street from Person p join Address d on d = p.address;  

我是否必须针对此特定情况为类Person和类Address创建构造函数?

感谢。

2 个答案:

答案 0 :(得分:0)

您的where条件无效:

select p.name, d.street from Person p join Address d on d = p.address;  

应该是这样的:

select p.name, d.street from Person p join Address d on d.person_id = p.id;  

或:

select p.name, d.street from Person p join Address d on d.id = p.address_id;  

以及类Person的构造函数的示例:

//cTor I
public Person(Integer id, String name, Address address){
    this.id = id;
    this.name = name;
    this.address = address;
}

//cTor II
public Person(Integer id, String name, Integer addressId, String street, String number){
    this.id = id;
    this.name = name;
    this.address = new Address(addressId, street, number);
}

答案 1 :(得分:0)

来自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(查询).getResultList();