title: Many-To-One with join Table in hibernate resource classes for a JAX-RS using Jersey
body: <p>I am implementing a RESTful Web Service using Jersey. I use hibernate to communicate with the database (mySQL). My hibernate resource classes includes:</p>
  
  <pre><code>@Entity
  public class Activity {
  
      @Id
      @GeneratedValue
      private long id;
  
  @ManyToOne
      @JoinTable(name="category_activity",
      joinColumns={@JoinColumn(name="activities_id")},
      inverseJoinColumns={@JoinColumn(name="Category_id")})
      private Category category;
  }
  </code></pre>
  
  <p>and the Category class:</p>
  
  <pre><code>@Entity
  public class Category {
  
      @Id
      @GeneratedValue
      private long id;
  
      @OneToMany
      @Fetch(FetchMode.JOIN)
      @JoinTable(name = "category_activity",
      joinColumns = { @JoinColumn(name = "Category_id") }, 
      inverseJoinColumns = { @JoinColumn(name = "activities_id") })
      @JsonIgnore
      private Collection&lt;Activity&gt; activities;
  }
  </code></pre>
  
  <p>I used this query to fetch the ativities:</p>
  
  <pre><code>session.createQuery("from Activity a join a.category cs where cs.id= :categoryId order by a.key").setLong("categoryId", categoryId).list();
  </code></pre>
  
  <p>The result in JSON format is not right like: </p>
  
  <pre><code>[[{"id":26,"key":"other","name":"Other","cost":100.0,"category":{"id":10,"name":"General","description":""}},{"id":10,"name":"General","description":""}]]
  </code></pre>
  
  <p>As you see category is printed 2 times and we have a extra [] around it. 
  When I use another mechanism of One-To-Many relation in Category class like:</p>
  
  <pre><code>@OneToMany(targetEntity = Activity.class, mappedBy = "category", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
  @JsonIgnore
  private Collection&lt;Project&gt; activities;
  </code></pre>
  
  <p>And in Activity class: </p>
  
  <pre><code>@ManyToOne(optional = false)
      private Category category;
  </code></pre>
  
  <p>And this query:</p>
  
  <pre><code>session.createQuery("from Activity as a where a.category.id= :categoryId order by a.key").setLong("categoryId", categoryId).list();
  </code></pre>
  
  <p>Everything works fine. But I have to use join table because I do not suppose to change the database.</p>
  
  <p>The proper result should look like: </p>
  
  <pre><code>[{"id":26,"key":"other","name":"Other","cost":100.0,"category":{"id":10,"name":"General","description":""}}]
  </code></pre>
  
  <p>I appreciate for any help.</p>