JPA : How to convert a native query result set to POJO class collection

后端 未结 21 1798
孤街浪徒
孤街浪徒 2020-11-22 09:23

I am using JPA in my project.

I came to a query in which I need to make join operation on five tables. So I created a native query which returns five fields.

21条回答
  •  不知归路
    2020-11-22 09:40

    Use DTO Design Pattern. It was used in EJB 2.0. Entity was container managed. DTO Design Pattern is used to solve this problem. But, it might be use now, when the application is developed Server Side and Client Side separately.DTO is used when Server side doesn't want to pass/return Entity with annotation to Client Side.

    DTO Example :

    PersonEntity.java

    @Entity
    public class PersonEntity {
        @Id
        private String id;
        private String address;
    
        public PersonEntity(){
    
        }
        public PersonEntity(String id, String address) {
            this.id = id;
            this.address = address;
        }
        //getter and setter
    
    }
    

    PersonDTO.java

    public class PersonDTO {
        private String id;
        private String address;
    
        public PersonDTO() {
        }
        public PersonDTO(String id, String address) {
            this.id = id;
            this.address = address;
        }
    
        //getter and setter 
    }
    

    DTOBuilder.java

    public class DTOBuilder() {
        public static PersonDTO buildPersonDTO(PersonEntity person) {
            return new PersonDTO(person.getId(). person.getAddress());
        }
    }
    

    EntityBuilder.java <-- it mide be need

    public class EntityBuilder() {
        public static PersonEntity buildPersonEntity(PersonDTO person) {
            return new PersonEntity(person.getId(). person.getAddress());
        }
    }
    

提交回复
热议问题