Announcement Announcement Module
Collapse
No announcement yet.
Tricky query question using QueryDSL & SD JPA Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Tricky query question using QueryDSL & SD JPA

    Ok, I've got two entities from a legacy codebase involved in this query, and I'm not sure how to combine them. I'm also using Spring Data JPA with QueryDSL. Entities first:
    Code:
    @Entity public class Foo {
      @Id Long id;
      String name;
      // other attributes...
    }
    Code:
    @Entity public class Bar {
      @Id Long id;
      Long fooId; // NOTE: the Foo id, **not** the entity
      String status;
      // other attributes...
    }
    Note that Foo has no knowledge of its Bars, and Bar has a many-to-one relationship to Foo, but manifested as an attribute holding the id of the Foo (not a @ManyToOne Foo foo -- remember, this is a legacy codebase).

    Now, I want to find all Foos with a given name where there exists at least one Bar with a given id and a status that is not "DELETED" and whose fooId is equal to the corresponding Foo's id. How would I formulate that query using QueryDSL?
    Code:
    // method impl inside custom SD JPA QueryDslPredicateExecutor<Foo> repository
    
    public List<Foo> findByNameWithNotDeletedBarAndBarFooId(String name, long barId) {
      QFoo foo = QFoo.foo; // generated by QueryDSL APT
      QBar bar = QBar.bar; // generated by QueryDSL APT
    
      Predicate p = new BooleanBuilder()
        .and(name != null && (name = name.trim()).length() > 0 ? foo.name.eq(name) : null)
        .and(bar.id.eq(barId))
        .and(bar.status.ne("DELETED"));
      
      // how can you include condition "where bar.fooId equals foo.id" & combine with Predicate p?
    
      return findAll(???);
    }
Working...
X