0

I have this class for example:

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

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

    ...
}

I would like a build CriteriaQuery in JPA for this SQL

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

Do I have to create a Constructor for class Person and class Address for this particular situation?

Thanks.

4

2 回答 2

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(query).getResultList();

于 2013-12-09T11:45:36.637 回答
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);
}
于 2012-08-24T18:05:04.293 回答