title: How do I create an object with nested objects using Hibernate?
body: <p>I'm getting the following exception:</p>
  
  <pre><code>Referential integrity constraint violation: "FK779B6FDFD4D56C1: PUBLIC.LOG_TAG FOREIGN KEY(PEOPLE_ID) REFERENCES PUBLIC.TAG(ID)";
  </code></pre>
  
  <p>Here's what I'm trying to do:</p>
  
  <pre><code>Set&lt;String&gt; tagList = getTags();
  Log log = new Log(content, user);
  log.addTags(tagList);
  log.save();
  </code></pre>
  
  <p>I think understand the error (trying to save an object with a reference to an object that hasn't been saved yet), but I've tried every combination of order of saving each object, and nothing seems to be working. I'm looking at the Play Framework tutorial for creating a blog as a reference. Here's my model class:</p>
  
  <pre><code>@Entity
  public class Log extends Model {
      @Lob
      public String content;
  
      @ManyToOne
      public User author;
  
      @ManyToMany(cascade=CascadeType.PERSIST)
      public Set&lt;Tag&gt; tags;
  
      public Log(String content, User author) {
          this.author = author;
          this.content = content;
          this.tags = new TreeSet&lt;Tag&gt;();
      }
  
      public void addTags(Set&lt;String&gt; tags) {
          for (String tag : tags) {
              Tag newTag = Tag.findOrCreateByName(tag); //since the DB is empty, this method is simply creating and .save()'ing tags
              this.tags.add(newTag);
          }
      }
  }
  </code></pre>
  
  <p>Right now the Tag class is a simple entity that only has one field.</p>
  
  <p>What am I doing wrong here? How do I make this work?</p>