Query dsl with predicate and fetch join

时间:2018-06-04 17:03:37

标签: java spring-data spring-data-jpa querydsl

is there a chance to fetch join entity with using predicate?

    @Entity
public class Student {

    @Id
    private int id;

    private String hobby;

    private String favouriteColor;

    private String name;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
    @JoinColumn(name = "CLASS_ID", referencedColumnName = "ID")
    private Classroom classroom;
}

@Entity
public class Classroom {

    @Id
    private int id;

    private String classRoom;

    private List<Student> students;

}

I have some predicate

public class StudentPredicate {

    private StudentPredicate() {}

    public static Predicate createPredicate(final Student filter) {
        QStudent student = QStudent.student;

        BooleanBuilder builder = new BooleanBuilder();

        if (isNotBlank(filter.getHobby())) {
            builder.and(student.hobby.eq(filter.getHobby());
        }
        if (isNotBlank(filter.getFavouriteColor())) {
            builder.and(student.favouriteColor.eq(filter.getFavouriteColor()));
        }


        return builder.getValue();
    }

}

and repository

@Repository
public interface StudentRepository extends CrudRepository<Student, Integer>, QueryDslPredicateExecutor<Student> {

}

and now how can I find all students with fetched classrooms?

studentRepository.findAll(predicate)

How to say to query dsl that these findAll should fetch classroom?

1 个答案:

答案 0 :(得分:0)

As there's FetchType.LAZY for classroom field in Student class, so here while you call getClassRoom() will actually fetch the related entity from db or either you can use FetchType.EAGER.