title: How to build recursive join with condition using CriteriaBuilder
body: <p>In my application, I have the following data structure with parent - child relation to other objects of the same class, which looks like following:</p>
  
  <pre class="lang-java prettyprint-override"><code>@Entity
  public class CoreData {
      ...
      @ManyToOne(fetch = FetchType.LAZY)
      @JoinColumn(name = "PARENT_CORE_ID")
      private CoreData parentCoreData;
      ...
      @OneToMany(mappedBy = "parentCoreData", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
      private List&lt;CoreData &gt; childCoreData;
      ...
      private String someStringValue;
      private String coreType;
  }
  </code></pre>
  
  <p>I would like to build a query using Criteria builder to fetch all CoreData objects of given coreType which meet one of the following conditions:</p>
  
  <ul>
  <li><code>coreData.coreType == searchedCoreType</code></li>
  </ul>
  
  <p><strong>AND (</strong></p>
  
  <ul>
  <li><code>someStringValue == searchedCoreStringValue</code></li>
  </ul>
  
  <p>OR</p>
  
  <ul>
  <li>coreData's top parent meets condition <code>someStringValue == searchedCoreStringValue</code></li>
  </ul>
  
  <p><strong>)</strong></p>
  
  <p>Additionally, I know that there are no cycles of any depth in child-parent relation.</p>
  
  <p>I don't know where to start with building the query. Since I'm looking for lowest children which meet criteria, it would suggest I have to do the following logic with criteria builder:</p>
  
  <pre class="lang-java prettyprint-override"><code>checkParentCore(core, conditionString) {
      if(core.parentCore == null) {
           if(core.someStringValue == conditionString) {
               return true;
           } else {
               return false;
           }
       } else {
            return checkParentCore(core.parentCore, conditionString)
       }
  }
  </code></pre>
  
  <p>However, I have no idea how to do so since it would require some kind of recursive conditional join on the pre-filtered list. Also, this seems very inefficient performance-wise.</p>
  
  <p>Is there a better solution to this problem? </p>
  
  <p>If not then how can I build a recursive conditional join with CriteriaBuilder?</p>