title: Hibernate JPA bidirectional one-to-many results with constraint violation exception
body: <p>I started to learn hibernate JPA and I try to create bidirectional one-to-many relation, but for some reason it results with <code>org.hibernate.exception.ConstraintViolationException: could not execute statement</code></p>
  <p>Let's say I have an entity Card and entity Deck. And each Deck can have multiple cards, but every card can belong only to single deck. I made it this way:</p>
  <p>This is the card entity:</p>
  <pre><code>/**
   * Represents a card in deck.
   *
   * @author wintermute
   */
  @Data
  @Entity(name = &quot;card&quot;)
  @Table(name = &quot;card&quot;)
  @NamedQueries( {@NamedQuery(name = &quot;Card.getAll&quot;, query = &quot;SELECT c FROM card c WHERE c.containedInDeck = :deck_id&quot;),
                  @NamedQuery(name = &quot;Card.remove&quot;, query = &quot;DELETE FROM card c WHERE c.id = :id&quot;)})
  public class Card
  {
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private long id;
      private String containedText;
  
      @ManyToOne
      @JoinColumn(name = &quot;deck_id&quot;)
      private Deck containedInDeck;
  }
  </code></pre>
  <p>And this is the deck:</p>
  <pre><code>/**
   * Represents card deck containing cards sorted by deck's type.
   *
   * @author wintermute
   */
  @Data
  @Entity
  @Table(name = &quot;deck&quot;)
  public class Deck
  {
      @Id
      @GeneratedValue
      private long id;
      @Column(name = &quot;type&quot;)
      private String typeOfDeck;
  
      @OneToMany(mappedBy = &quot;containedInDeck&quot;)
      @ElementCollection(targetClass = Card.class)
      private Set&lt;Card&gt; containedCards = new HashSet&lt;&gt;();
  }
  </code></pre>
  <p>Now this is my repository where I want to persist the card entity:</p>
  <pre><code>    ...
      /**
       * @param card to persist in database.
       * @return true if operation was successful, false if operation failed.
       */
      public long add(Card card)
      {
          try
          {
              entityManager.getTransaction().begin();
              entityManager.persist(card);
              entityManager.flush();
              entityManager.getTransaction().commit();
              return card.getId();
          } catch (IllegalStateException | PersistenceException e)
          {
              log.error(&quot;Could not save entity: &quot; + card + &quot;, message: &quot; + e.getMessage());
              return -1L;
          }
      }
      ...
  </code></pre>
  <p>While executing <code>entityManager.flush()</code> it crashes because of violated constraint. I can't just imagine why.</p>