title: JPQL - implement conditional logic based on most recent element
body: <p>I'm new to JPA and Spring data. I would like to implement a function with the following logic in my ordering system:</p>
  
  <ol>
  <li>If no order after given timestamp, return 1</li>
  <li>otherwise return last order's counter+1</li>
  </ol>
  
  <p>Can I implement such logic with Pure JPQL?</p>
  
  <p>Order entity:</p>
  
  <pre><code>@Entity
  public class Order {
  
      @Id
      @GeneratedValue
      private UUID id;
  
      private Integer counter;
  
      @CreationTimestamp
      private Timestamp creationTimestamp;
  
      ...
  </code></pre>
  
  <p>OrderRepository.java:</p>
  
  <pre><code>@Repository
  public interface OrderRepository extends CrudRepository&lt;Order, UUID&gt; {
  
      // TODO what goes after else?
      @Query("select case when count(o) &lt; 1 then 1 else ... from Order o where o.creationTimestamp &gt; :timestamp order by o.creationTimestamp desc")
      Integer nextCounter(@Param("timestamp") Timestamp timestamp);
  
  }
  </code></pre>