title: How can I insert value to `@OrderBy` mapped columns automaticly in JPA/Hibernate?
body: <p>I have related entities: One <code>User</code> -> many <code>Orders</code>.</p>
  
  <pre><code>    @OneToMany(mappedBy = "user", cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = LAZY)
      private List&lt;Order&gt; orders;
  </code></pre>
  
  <p>I want to get ordered orders when I select the user and get all orders from it. I can create a new field in the orders table <code>ordinal_number</code> and add <code>@OrderBy</code> annotation:</p>
  
  <pre><code>@OrderBy("ordinal_number")
  @OneToMany(mappedBy = "user", cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = LAZY)
  private List&lt;Order&gt; orders;
  </code></pre>
  
  <p>But I don't understand how can I insert correct value to <code>ordinal_number</code> during save. I create user, create a list of orders, add a user to each order and add list orders to the user. And save the user. 
  The primitive way -  create an int variable, add it manually to each order and increment.  But maybe there are some ways do it automatically? (for example, add some generator, autoincrement or something other)?</p>
  
  <p>EDIT:</p>
  
  <p>My order class:</p>
  
  <pre><code>EqualsAndHashCode(exclude = "user")
  @Data
  @Entity
  @Table(name = "orders")
  public class Order {
  
      @Id
      private String id;
  
      @Column(name = "name")
      private String name;
  
      @Temporal(TemporalType.TIMESTAMP)
      @Column(name = "insert_date")
      private Date insertDate = new Date();
  
      @Column(name = "ordinal_number")
      private Integer ordinalNumber;
  
      @ManyToOne(fetch = FetchType.LAZY)
      @JoinColumn(name = "user_id", nullable = false)
      private User user;
  }
  </code></pre>
  
  <p>My User class:</p>
  
  <pre><code>@ToString(exclude = "orders")
  @Data
  @Entity
  @Table(name = "users")
  public class User {
  
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Long id;
  
      @Column(name = "name")
      private String name;
  
      @OrderColumn(name = "ordinal_number")
      @OneToMany(mappedBy = "user", cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = LAZY)
      private List&lt;Order&gt; orders;
  }
  </code></pre>