title: How to sort JPA entities using TreeSet
body: <p>I have a few entity beans with sets of other entities as attributes. I want to sort them and guarantee that at every insertion they will remain sorted.
  I tried this way:</p>
  
  <pre><code>@Entity
  @Table(name = "Document")
  public class Document implements Serializable, Comparable&lt;Document&gt; {
  
      ...
  
      @ManyToOne
      private Project relativeProject;
  
      ...
  
      @Override
      public int compareTo(Document d) {
          long data1 = getDate().getTimeInMillis();
          long data2 = d.getDate().getTimeInMillis();
          if(data1 &gt; data2)
              return 1;
          else
              if(data2 &lt; data1)
                  return -1;
              else
                  return 0;
      }
  
      @Override
      public boolean equals(Object d) {
          return (getIdDocument() == ((Document)d).getIdDocument());
      }
  
      @Override
      public int hashCode() {
          return Long.valueOf(getIdDocument()).hashCode();
      }
  
  }
  
  
  
  
  @Entity
  @Table(name="Project")
  public class Project implements Serializable, Comparable&lt;Project&gt; {
  
      ...
  
      @OneToMany(mappedBy="relativeProject", fetch = FetchType.EAGER)
      @Sort(type = SortType.NATURAL)
      private SortedSet&lt;Document&gt; formedByDocuments;
  
      public Progetto() {
          this.formedByDocuments = new TreeSet&lt;Document&gt;();
      }
  
      ...
  
  }
  </code></pre>
  
  <p>But it does not work. The problem is that, even if in the database there are all needed entries, when a session bean returns a <code>Project</code> there will miss some <code>Document</code>. Moreover, entries are not sorted at all in the database.
  <br>
  If I do not sort at all (using <code>HashSet</code>) and republish the project, everything works fine and I get all the elements in a set (but not sorted, of course).
  <br>
  Can someone help me to find out what's wrong with my sorting?</p>