很多时候表与表之间是有关系的,比如一对一 一对多等等,也有的没有建立起 关系只是存了主键id 。

此时多表查询可以使用left join

代码如下:

        QUser qUser = QUser.user;
        QStudent qStudent = QStudent.student;
        String userName = "张三";
        String bloodType = "AB";
        Predicate predicate = qUser.id.isNotNull().or(qUser.isNull());
        predicate = StringUtils.isEmpty(userName) ? predicate : ExpressionUtils.and(predicate, qUser.name.eq(userName));
        predicate = StringUtils.isEmpty(bloodType) ? predicate : ExpressionUtils.and(predicate, qStudent.bloodType.eq(bloodType));

        //连表查询
        List<UserStudentDTO> userStudentDTOList = jpaQueryFactory.select(
                Projections.bean(
                        UserStudentDTO.class,
                        qUser.address.as("address2"),
                        qStudent.birthday
                )
        )
                .from(qUser)
                .leftJoin(qStudent)
                .on(qUser.id.eq(qStudent.id))
                .where(
                        predicate,
                        qStudent.isdelete.eq(false),
                        qUser.isdelete.eq(false)
                )
                .fetch();

执行的sql:

Hibernate: 
    select
        user0_.address as col_0_0_,
        student1_.birthday as col_1_0_ 
    from
        smms_user user0_ 
    left outer join
        smms_student student1_ 
            on (
                user0_.id=student1_.id
            ) 
    where
        (
            user0_.id is not null 
            or user0_.id is null
        ) 
        and user0_.name=? 
        and student1_.blood_type=? 
        and student1_.isdelete=? 
        and user0_.isdelete=?

然后看下集合中的值:

Spring Data JPA QueryDSL 多表联合查询_经验分享

Predicate可以创建动态的查询条件,不需要的话也可以直接在where中写
Projections是自定义返回对象的