springjpa(五)QueryDsl查询细
上一篇中有讲过,如果多表关联查询时(上节4.3)想将多表的中不同字段选出来时,咱们用的是java8语法将list组装,那么有没有不需要自行组装这一步,查询返回的结果自动就帮我们组装好了呢?
这边介绍个简便方法,使用Projections。
首先我们还是以学校和学生表作为例子。
这边我们先建一个StudentDto
public class StudentDto { private long id; private String name; private int age; private long schoolId; private String schoolName; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public long getSchoolId() { return schoolId; } public void setSchoolId(long schoolId) { this.schoolId = schoolId; } public String getSchoolName() { return schoolName; } public void setSchoolName(String schoolName) { this.schoolName = schoolName; } @Override public String toString() { return "StudentDto{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", schoolId=" + schoolId + ", schoolName='" + schoolName + '\'' + '}'; } }
这里包含我们想要的学生id,姓名,年龄,学校id,学校名称等字段。
将上节4.3的代码修改成如下
@Test public void selectStudent5() { QStudent qStudent = QStudent.student; QSchool qSchool = QSchool.school; List<StudentDto> students = queryFactory .select(Projections .fields(StudentDto.class, qStudent.id, qStudent.name, qStudent.age, qStudent.schoolId, qSchool.name.as("schoolName"))) .from(qSchool, qStudent) .where(qSchool.id.eq(qStudent.schoolId)) .fetch(); System.out.println(students); }
返回的结果就自动拼装成了我们想要的StudentDto。
当然了,如果不想要每次都定义Dto,那么还是可以用上节4.3的那种方式组装成一个map。