title: JPA get MIN/MAX attribute of connected entity
body: <p>Consider the following two entities:</p>
  
  <pre><code>@Entity
  public class HostMachine {
      @ManyToMany(fetch = FetchType.LAZY, targetEntity = Application.class)
      private Set&lt;Application&gt; applications;
  
      // getters and setters
  }
  </code></pre>
  
  <p>.</p>
  
  <pre><code>@Entity
  public class Application {
      @Basic
      @Enumerated(EnumType.STRING)
      private BusinessCriticality businessCriticality;
  
      @ManyToMany(fetch = FetchType.LAZY, targetEntity = HostMachine.class, mappedBy = "applications")
      private Set&lt;HostMachine&gt; hosts;
  
      // getters and setters
  }
  </code></pre>
  
  <p>A classic <code>ManytoMany</code> relationship. <strong>Now I want to see the highest businessCriticality of connected applications on the host.</strong></p>
  
  <p>I tried using a <code>@Transient</code> attribute and setting it after every single query that returns hosts, but for collections I'd need to do a query for every single element, so this is very un-performant and straight ugly in code.</p>
  
  <p>Then I tried using Hibernate's <code>@Formula</code>:</p>
  
  <pre><code>@Formula("SELECT MIN(a.businessCriticality) FROM Application a")
  private BusinessCriticality businessCriticality;
  </code></pre>
  
  <p>but this gives me a <code>MySQLSyntaxErrorException</code>, even though I can execute the query in an MySQL client.</p>