title: How to map an intermediate table in Hibernate
body: <p>I wish to map an intermediate table that looks like this:</p>
  <p><a href="https://i.stack.imgur.com/12k0j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/12k0j.png" alt="" /></a></p>
  <p>This is how my user class looks:</p>
  <pre><code>@Entity
  @Table(name = &quot;users&quot;)
  public class User
  
  @Id
  @Column(name = &quot;user_id&quot;)
  private int id;
  
  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  @JoinTable(name=&quot;FAVORITES&quot;,
  joinColumns = @JoinColumn(name = &quot;fk_user_id&quot;, 
                            referencedColumnName = &quot;user_id&quot;), 
  inverseJoinColumns = @JoinColumn(name = &quot;fk_content_id&quot;, 
                            referencedColumnName = &quot;content_id&quot;))
  private Set&lt;Content&gt; favorites;
  </code></pre>
  <p>And this is how my content class looks:</p>
  <pre><code>@Entity
  @Table(name = &quot;content&quot;)
  public class Content
  
  @Id
  @Column(name=&quot;content_id&quot;)
  private int id;
  </code></pre>
  <p>The objects persist correctly, but not in the favorites table, instead only the ids 0 are saved.</p>
  <p>Where i create the objects:</p>
  <pre><code>public void registerUser(User tempUser) {
      Session session = this.SessionFactory.getCurrentSession();
      session.beginTransaction();
      Content con = new Content();
      Set&lt;Content&gt; favs = new HashSet&lt;Content&gt;();
      favs.add(con);
      tempUser.setFavorites(favs);
      session.save(tempUser);
      session.getTransaction().commit();
      session.close();
  }
  </code></pre>
  <p>And a log:</p>
  <pre><code>Hibernate: select content_.content_id from contents content_ where content_.content_id=?
  Hibernate: insert into users (user_id) values (?)
  Hibernate: insert into contents (content_id) values (?)
  Hibernate: insert into FAVORITES (fk_user_id, fk_content_id) values (?, ?)
  </code></pre>
  <p>Image of what is persisted in the DB:</p>
  <p><a href="https://i.stack.imgur.com/8LhS6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8LhS6.png" alt="" /></a></p>