How to group by projections with Hibernate

纵饮孤独 提交于 2019-12-06 03:53:40

The AliasToBeanNestedResultTransformer supports nested DTOs but it doesn not support Collections of DTOs.

You can change the AllStudent DTS to:

public class AllStudents {
    Student student;
    String phone;
    Location location;

    public AllStudents(Student student, String phone, Location location) {
        this.student = student;
        this.phone = phone;
        this.location = location;
    }

    public Student getStudent() {
        return student;
    }

    public String getPhone() {
        return phone;
    }

    public Location getLocation() {
        return location;
    }
}

and you need to add a StudentDTO to hold the aggregation result:

public class StudentDTO {
    private final Student student;
    private String location;
    private List<String> phones = new ArrayList<>();

    public StudentDTO(Student student) {
        this.student = student;
    }

    public Student getStudent() {
        return student;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public List<String> getPhones() {
        return phones;
    }
}

Now when you run your query you get a List of AllStudents:

List<AllStudents> allStudents = ...

which you simply group like this:

LinkedHashMap<Long, StudentDTO> studentMap = new LinkedHashMap<>();

for(AllStudents all : allStudents) {
    StudentDTO studentDTO = studentMap.get(all.getStudent().getId());
    if(studentDTO == null) {
        studentDTO = new StudentDTO(all.getStudent());
        studentMap.put(all.getStudent().getId(), studentDTO);
    }
    if(all.getPhone() != null) {
        studentDTO.getPhones().add(all.getPhone());
    }
    studentDTO.setLocation(all.getLocation());
}

List<StudentDTO> studentDTOs = new ArrayList<>(studentMap.values());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!