title: Error inserting new parent-child records in transaction using Spring JDBC
body: <p>I have 2 tables (Item and Code) with relation one to many(one Item can have many Codes - this is implemented on db level with foreign key). </p>
  
  <p>When I am trying to insert one Item record and several Code records(they are linked to that Item record) in one transaction using spring JDBC I get </p>
  
  <pre><code>com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`mrbcodes`.`code`, CONSTRAINT `code_item_fk` FOREIGN KEY (`itemId`) REFERENCES `item` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
  </code></pre>
  
  <p>Here is my insert into db code.</p>
  
  <pre><code>public void saveCode(Code code, long itemId) {
    String insertSql = "insert into code(number, value, itemId) values (:number,:value,:itemId)";
    SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(code);
    log.info("Inserting values into code table; number:" + code.getNumber() +"; value:" + code.getValue() 
      + "; itemId:" + itemId);
    simpleJdbcTemplate.update(insertSql, namedParameters);
   }
  
   @Transactional
   public void saveCodes(Collection &lt;Code&gt; codes) {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    insertNewItem(keyHolder);  
    Number key = keyHolder.getKey();
    Assert.notNull(key, "After item insert; returned key must not be null");
    for (Code code:codes) {
     saveCode(code, key.longValue());
    }
   }
  
   private KeyHolder insertNewItem(KeyHolder keyHolder) {
    String createItemSQL = "insert into item(timeUsed) values(:defaultValue)";  
    SqlParameterSource sqlParameterSource = new MapSqlParameterSource("defaultValue", defaultValue);
    log.debug("Inserting new item");
    simpleJdbcTemplate.getNamedParameterJdbcOperations().update(createItemSQL,sqlParameterSource, keyHolder);
    log.debug("Item inserted; keyHolder " + keyHolder);
    return keyHolder;
   }
  </code></pre>