简体   繁体   中英

Is there a way to build Objects from an inner class inside of a SELECT statement in JPQL?

I'm trying to build an object from an inner class inside a SELECT statement in JPQL.

I'm extracting data from an entity and using them to build a DTO. Something like this:

SELECT new project.models.dtos.RequestDTO(r.id, 
       t.id,
       t.description, 
       ...) 
FROM Request r 
JOIN Topic t. etc.

Now, this RequestDTO has some inner classes, that are based on the original entity, and they are used in the constructor, like this:

public class RequestDTO{
    private Long id;
    private TopicDTO topic;

    public class TopicDTO{
        private Long id;
        private String description;
    }

    public RequestDTO(Long id, TopicDTO topic, ...){
        this.id = id;
        this.topic = topic
    }
}

What i would like to do is build the inner objects DIRECTLY inside of the select statement of the main query, like so:

SELECT new project.models.dtos.RequestDTO(
       r.id, 
       new project.models.dtos.RequestDTO.TopicDTO(
           t.id, 
           t.description),
       r.stuff,
       ...) 
FROM Request r 
JOIN Topic t 
etc.

Is there a way to do so? Thanks in advance!

I don't think that's possible. One option to workaround this would be to create a constructor of RequestDTO that also builds TopicDTO by some parameters:

public class RequestDTO{
    private Long id;
    private TopicDTO topic;

    public RequestDTO(Long id, Long topicId, String topicDescription, ...){
        this.id = id;
        this.topic = new TopicDto(topicId, topicDescription);
    }

    public class TopicDTO{
        private Long id;
        private String description;
        // Constructor, getter, setter
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM