JPA- Joining two tables in non-entity class

后端 未结 3 1078
情书的邮戳
情书的邮戳 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 01:51

    @SqlResultSetMapping can be placed at any entity class (don't annotate POJOs - it won't work). Mapping to POJO class with @ConstructorResult was added in version 2.1 of JPA. POJO used with the mapping has to have correct constructor.

    All columns corresponding to arguments of the intended constructor must be specified using the columns element of the ConstructorResult annotation in the same order as that of the argument list of the constructor.

    Please consult following example with query usage and work out your case accordingly.

    @Entity
    public class Address {
        @Id int id;  
        String street;
    }
    
    
    @SqlResultSetMapping(name="PersonDTOMapping",
        classes = {
         @ConstructorResult(targetClass = PersonDTO.class,
           columns = {@ColumnResult(name="name"), @ColumnResult(name="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;
        }
    }
    
    // usage
    Query query = em.createNativeQuery(
        "SELECT p.name AS name, a.street AS street FROM Person p, Address a WHERE p.address_id=a.id",
        "PersonDTOMapping");
    List result = query.getResultList();
    

    Please note that aliases (AS name and AS street) has to match the names in @ColumnResults. The example was tested against Ecliselink 2.5.1.

提交回复
热议问题