if (pkFields.size() == 1) {
pkFields.get(0).setAccessible(true);
pkFields.get(0).set(entity, id);
} else {
// A compound key cannot be auto-generated
throw new InternalErrorException("DefaultDAOImpl::insert -> A compound key cannot be auto-generated. (" + entity + ")");
}
}
// Get the query
String query = ModelUtilities.getQueryForInsert(entity.getClass());
String[] fieldNames = query.substring(query.indexOf('(') + 1, query.indexOf(')')).split(",");
// Prepare query
stm = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
// Fill query
for (int i = 0; i < fieldNames.length; i++) {
logger.log(Level.INFO, "Value we set into insert query: " + fieldNames[i] + " -- " +
ModelUtilities.getFieldValue(fieldNames[i], entity));
ModelUtilities.insertValueInQuery(ModelUtilities.getFieldValue(fieldNames[i], entity), stm, (i + 1));
}
// Execute insert query
int i = stm.executeUpdate();
// If database generated PK, we need to get it
if (entityId == null && !entity.getClass().getAnnotation(PersistentEntity.class).generateKey()) {
ResultSet pkRs = stm.getGeneratedKeys();
if (pkRs != null) {
if (pkRs.next()) {
List<Field> pkFields = ModelUtilities.getEntityIdentifierFields(entity.getClass());
if (pkFields.size() == 1) {
Field pkField = pkFields.get(0);
pkField.setAccessible(true);
// ResultSetMetaData rsmd = pkRs.getMetaData();
pkField.set(entity, ModelUtilities.getValueFromQuery(pkField.getType(), pkRs, 1));
} else {
// A compound key cannot be auto-generated
throw new InternalErrorException("DefaultDAOImpl::insert -> A compound key cannot be auto-generated. (" + entity + ")");
}
} else {
throw new InternalErrorException("ERROR: COULD NOT RETRIEVE PK GENERATED BY DATBASE.");
}
} else {
throw new AutogeneratedKeysReturnNotSupportedException();
}
}
// We must have inserted exactly one row
if (i != 1) {
throw new InternalErrorException("ERROR: INSERT METHOD FAILED. " + i + " records have been inserted. (" + entity + ")");
}
} catch (SQLException e) {
logger.log(Level.SEVERE, "SQL Exception while inserting: " + e.getMessage(), e);
throw new InternalErrorException("Database Exception while inserting.... (" + entity + ")", e);
} catch (IllegalAccessException e) {
logger.log(Level.SEVERE, "Reflection exception while inserting (" + entity + "): " + e.getMessage(), e);
throw new ReflectionException(e);
} finally {
closeResouces(stm, null);