1
votes

I'm just getting started using QueryDSL with Spring Data JPA. I have a class where I'm storing all of my predicates, so that in my service methods, I can just call findAll() or findOne() on my repositories by passing in the boolean expression. Here's an example:

Predicate class method:

public static BooleanExpression byCode(String code) {

  return QHeading.heading.code.eq(code);

}

Service class method:

public Iterable<Heading> getByCode(final String code) {

  return headingRepository.findAll(byCode(code));

}

This works fine, but in the case where one heading is the child of another heading, I'd like to reuse the same method from my predicate class, just wrapping it in another method that returns the parent heading, rather than the child that matches the boolean expression. However, I'm having a bit of trouble figuring out the correct way to do this.

So, it would be something like this:

Predicate methods:

public static BooleanExpression byCode(String code) {

  return QHeading.heading.code.eq(code);

}

public static BooleanExpression byChildCode(String code) {

  QHeading.heading.childHeadings.eq(byCode(code));

}

Service method:

public Iterable<Heading> getByChildCode(final String code) {

  return headingRepository.findAll(byChildCode(code));

}

Obviously, the eq() method doesn't work, but is there a way to accomplish this, or is there a different way I should be going about this entirely?

1

1 Answers

3
votes

You can either do it like this

public static BooleanExpression byCode(String code) {
    return QHeading.heading.code.eq(code);
}

public static BooleanExpression byChildCode(String code) {
    return QHeading.heading.childHeadings.any().code.eq(code);
}

or if you want more code reusal:

private static BooleanExpression byCode(QHeading heading, String code) {
    return heading.code.eq(code);
}

public static BooleanExpression byCode(String code) {
    return byCode(QHeading.heading, code);
}

public static BooleanExpression byChildCode(String code) {
    return byCode(QHeading.heading.childHeadings.any(), code);
}