I am looping over a set of objects inserting them into my PostgreSQL database like this:
sql.withTransaction {
try {
sql.withBatch(1000, 'insert into category (id, version, name, parent_id) values (:id, :version, :name, :parent_id);') { stmt ->
categoryInserts.each {
try {
stmt.addBatch([id: it.id, version: 0, name: it.name, parent_id: it.parent?.id])
} catch (SQLException e) {
log.error("Category ${it.name} with parent ${it.parent?.id} could not be inserted.")
}
}
}
} catch (BatchUpdateException e) {
log.error("Categories could not be inserted.")
}
sql.commit()
}
There is a unique constraint (name, parent_id) on the category table. If the constraint is violated the program catches a BatchUpdateException and subsequent objects are not inserted. Unfortunately the exception is not thrown while executing the addBatch-method.
Is there any way to continue with the withBatch statement, so that duplicates are ignored and new records are inserted? It seems strange to me that a batch-Insert does not offer this behaviour.