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).
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
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)
Here is my insert into db 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 <Code> 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 Ke开发者_如何学CyHolder 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;
}
You don't use itemId
in saveCode
, therefore Code
is saved without itemId
.
精彩评论