admin管理员组

文章数量:1123873

I have the following entities in my database:

@Getter
@Entity
class TopLevel {
    @Column
    String name;
    @OneToMany
    List<SubTypeOne> subtypes;
}

@Getter
@Entity
class SubTypeOne {
    @ManyToOne()
    SubTypeTwo property
}

@Getter
@Entity
class SubTypeTwo {
    @Column
    int finalProperty
}

I have a DTO that looks like this:

record TopLevelDto(String name, Collection<Integer> subTypeTwoProperties) {}

I'd like to create a DTO object directly from within a JPA query using JPQL. Right now, I can build the required objects efficiently using the following code:

String query = """
               SELECT t
               FROM TopLevel t
               LEFT JOIN FETCH t.subtypes st
               LEFT JOIN FETCH st.property
               """
// code to get TopLevel Object from query omitted
TopLevel t = ??
List<Integer> subTypeTwoProperties = t.getSubtypes().stream()
    .map(s -> s.getProperty().getFinalProperty())
    .toList();
TopLevelDto dto = new TopLevelDto(t.getName(), subTypeTwoProperties);

Is there way to do all of this just within the JPQL query itself?

I would expect a function or some other mechanism to convert the st object in the query into a list. For example, I'm calling it collect_list here:

String query = """
               SELECT new TopLevelDto(t.name, collect_list(st.property))
               FROM TopLevel t
               LEFT JOIN FETCH t.subtypes st
               LEFT JOIN FETCH st.property
               """

Does something like this, or an alternative, exist?

本文标签: javaIs there a way to create lists of joined objects in JPA queriesStack Overflow