title: Hibernate cascade save parent and children - parent key not found
body: <p>I am using Spring, Hibernate and oracle for a project. The database schema was created manually by running sql script. Everything works fine until I encountered a problem with hibernate one-to-many bidirectional cascade save. </p>
  
  <p>In the parent class (Product.java)</p>
  
  <pre><code>@OneToMany(mappedBy="product",
          fetch=FetchType.EAGER,
          cascade={CascadeType.ALL})
  public Set&lt;Picture&gt; getPictures() {
          return pictures;
  }
  
  @Transient
  public void addPicture(Picture picture) {
      picture.setProduct(this);
      pictures.add(picture);
  }
  </code></pre>
  
  <p>In the child class (Picture.java)</p>
  
  <pre><code>@ManyToOne(cascade={CascadeType.ALL})
  @JoinColumn(name="lse09lse06id")
  public Product getProduct() {
          return product;
  }
  </code></pre>
  
  <p>"lse09lse06id" is the foreign key column in the child entity table. </p>
  
  <p>In my Controller class:</p>
  
  <pre><code>Product product = new Product();
  .... (set properties of product)
  Picture newPicture = new Picture();
  .... (set properties of newPicture)
  product.addPicture(newPicture);
  productService.addProduct(product);
  </code></pre>
  
  <p>In my ProductService class:</p>
  
  <pre><code>@Override
  @Transactional
  public void addProduct(Product product) {
      productDAO.addProduct(product);
  }
  </code></pre>
  
  <p>In my ProductDAO class:</p>
  
  <pre><code>@Override
  public void addProduct(Product product) {
      product.setDateCreated(new Date());
      sessionFactory.getCurrentSession().save(product);
  }
  </code></pre>
  
  <p>Exception thrown when the controller code is executed:</p>
  
  <blockquote>
    <p>org.springframework.web.util.NestedServletException:
    Request processing failed; nested
    exception is
    org.springframework.dao.DataIntegrityViolationException:
    Could not execute JDBC batch update;
    SQL [insert into lse09pictures
    (lse09content, lse09date_created,
    lse09date_deleted, lse09date_updated,
    lse09is_deleted, lse09lse06id,
    lse09id) values (?, ?, ?, ?, ?, ?,
    ?)]; constraint
    [CSSE3005GG.LSE09PICTURES_FK]; nested
    exception is
    org.hibernate.exception.ConstraintViolationException:
    Could not execute JDBC batch update</p>
  </blockquote>
  
  <p>One of the nested exception thrown:</p>
  
  <blockquote>
    <p>java.sql.BatchUpdateException:
    ORA-02291: integrity constraint
    (CSSE3005GG.LSE09PICTURES_FK) violated
    - parent key not found</p>
  </blockquote>
  
  <p>Any help would be much appreciated. This problem is really nasty. Thank you!</p>