JPA- Joining two tables in non-entity class

后端 未结 3 1099
情书的邮戳
情书的邮戳 2020-12-08 01:16

I am a newbie ,tried to google but I am unable to solve my query. Please help.

I am trying to map two entities : PersonA and Person in my POJO class PersonC

3条回答
  •  不知归路
    2020-12-08 02:03

    Just found a bit simpler solution using JPQL. I stole part of the example from @zbig's answer:

    @Entity
    public class Address {
        @Id int id;  
        String street;
    }
    
    @Entity
    public class Person {
        @Id int id;
        String name;
        Address address;  
    }  
    
    public class PersonDTO {
        String name;
        String street;
        public PersonDTO(String name, String street) {
            this.name = name;
            this.street = street;
        }
    }
    
    List listOfPersons = em.createQuery("select new com.example.PersonDTO(p.name, a.street) " +
    "from Person p, Address a " + 
    "WHERE p.address.id=a.id", PersonDTO.class).getResultList();
    

    The benefit of this solution is that you don't need to use the @SqlResultSetMapping annotation, which must be placed on any entity class, not the DTO class! And that's sometimes confusing because the entity class could only be partially related (when joining multiple tables for example).

    More info here

提交回复
热议问题