title: Java code for saving in Many-to-Many join table with extra columns JPA
body: <p>I have 2 tables Foo and Bar linked by join table FooBar. FooBar has some additional columns of its own. The foreign key from FooBar to Foo does not point to the primary key of Foo but to <code>foo_id</code> which has a uniqueness constraint.</p>
  <pre class="lang-java prettyprint-override"><code>@Entity
  public class Foo {
  
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Long id;
  
      private UUID fooId;
  
      @OneToMany(cascade = CascadeType.REMOVE, orphanRemoval = true)
      @JoinColumn(name = &quot;fooId&quot;, referencedColumnName = &quot;fooId&quot;)
      private List&lt;FooBar&gt; foobars;
  
  </code></pre>
  <pre class="lang-java prettyprint-override"><code>@Entity
  public class Bar {
  
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Long id;
  
      @Column
      private UUID barId;
  
      @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
      @JoinColumn(name = &quot;barId&quot;, referencedColumnName = &quot;id&quot;)
      private List&lt;FooBar&gt; foobars;
  
  </code></pre>
  <pre class="lang-java prettyprint-override"><code>@Entity
  public class FooBar {
  
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Long fooBarId;
  
      @JoinColumn(name = &quot;fooId&quot;, referencedColumnName = &quot;fooId&quot;,
                      insertable = false, updatable = false)
      @ManyToOne(fetch = FetchType.LAZY)
      private Foo foo;
  
      @Column
      private String x;
  
      @Column
      private String y;
  
      @ManyToOne(fetch = FetchType.LAZY)
      @JoinColumn(name = &quot;barId&quot;, referencedColumnName = &quot;id&quot; ,insertable = false, updatable = false)
      private Bar bar;
  
  </code></pre>
  <p>Usage: Foo table already has an entry for <code>foo_id</code>. I'm trying to save Bar and FooBar using the code below.</p>
  <pre class="lang-java prettyprint-override"><code>void doStuff() {
    // Foo already exists
    List&lt;FooBar&gt; refs = new ArrayList&lt;&gt;();
    refs.add(FooBar.builder()
                       .x(&quot;x&quot;)
                       .y(&quot;y&quot;)
                       .foo(Foo.builder()
                                 .fooId(the-foo-uuid)
                                 .build())
                       .build());
    Bar bar = new Bar();
    bar.setFoobars(refs);
    repo.saveAndFlush(bar);
  }
  </code></pre>
  <p>On executing the java code to save Bar and FooBar entries, I see a SQL constraint violation exception complaining that <code>foo_id</code> is null.</p>