StringBuilder buf = new StringBuilder("MERGE INTO ");
buf.append(tableName).append(" USING (VALUES(");
i = 0;
for (Entry<String, ColumnData> e : columnMap.entrySet()) {
Column column = e.getValue().column;
if (i != 0) buf.append(",");
buf.append("CAST(? AS ");
buf.append(column.getJdbcType().toString());
if (column.getScaleOrLength() > 0) {
buf.append("(").append(column.getScaleOrLength()).append(")");
}
buf.append(")");
i++;
}
buf.append(")) AS vals(");
i = 0;
for (String columnName : columnMap.keySet()) {
if (i != 0) buf.append(",");
buf.append(getVariable(columnName));
i++;
}
buf.append(") ON ").append(tableName).append(".").append(mapping.getPrimaryColumnName()).append("=vals.");
buf.append(getVariable(mapping.getPrimaryColumnName()));
buf.append(" WHEN MATCHED THEN UPDATE SET ");
i = 0;
for (String columnName : columnMap.keySet()) {
if (columnName.equals(mapping.getPrimaryColumnName())) {
continue;
}
if (i != 0) { buf.append(","); }
buf.append(tableName).append(".").append(columnName).append("=vals.");
buf.append(getVariable(columnName));
i++;
}
buf.append(" WHEN NOT MATCHED THEN INSERT (");
i = 0;
for (String columnName : columnMap.keySet()) {
if (i != 0) { buf.append(","); }
buf.append(columnName);
i++;
}
i = 0;
buf.append(") VALUES ");
for (String columnName : columnMap.keySet()) {
if (i != 0) { buf.append(","); }
buf.append("vals.").append(getVariable(columnName));
i++;
}
Column primaryColumn = mapping.getPrimaryColumn();
PreparedStatement insert = connection.prepareStatement(buf.toString());
int psIndex = 1;
for (Entry<String, ColumnData> e : columnMap.entrySet()) {
ColumnData cd = e.getValue();
Column column = cd.column;
if (column.getName().equals(primaryColumn.getName())) {
Object key = columnMap.get(primaryColumn.getName()).object;
if (primaryColumn.getScaleOrLength() > 0) {
insert.setObject(psIndex++, key,
primaryColumn.getJdbcType().getOrder(), primaryColumn.getScaleOrLength());
} else {