diff --git a/pom.xml b/pom.xml index 8735843..2f8397d 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ cz.foresttech ForestDatabase - 1.0.2 + 1.0.3 17 diff --git a/src/main/java/cz/foresttech/database/DatabaseEntityConvertor.java b/src/main/java/cz/foresttech/database/DatabaseEntityConvertor.java index 46b1b17..c9e7576 100644 --- a/src/main/java/cz/foresttech/database/DatabaseEntityConvertor.java +++ b/src/main/java/cz/foresttech/database/DatabaseEntityConvertor.java @@ -198,11 +198,15 @@ public String insertOrUpdateScript(Class clazz, T object) throws IllegalA return null; } - String columns = processFieldsForScript(clazz, object, false); + String columns = getColumnsFromField(clazz); + String values = getValuesFromField(clazz, object); + + String updateSetValues = processFieldsForScript(clazz, object, false); + String conflictPolicy = getConflictPolicy(clazz); return String.format("INSERT INTO %s (%s) VALUES (%s) ON CONFLICT (%s) DO UPDATE SET (%s);", - tableName, columns, columns, conflictPolicy, columns); + tableName, columns, values, conflictPolicy, updateSetValues); } /** @@ -260,6 +264,42 @@ private String processFieldsForScript(Class clazz, T object, boolean forD return keys + " = " + values; } + private String getValuesFromField(Class clazz, T object) throws IllegalAccessException { + StringBuilder values = new StringBuilder(); + + for (Field field : clazz.getDeclaredFields()) { + field.setAccessible(true); + Column column = field.getAnnotation(Column.class); + if (column == null) continue; + String dbName = getDbName(field, column); + Object fieldValue = field.get(object); + DatabaseValueProcessor valueProcessor = databaseAPI.getProcessor(field.getType()); + + String processedValue = processFieldValue(fieldValue, valueProcessor); + values.append(processedValue).append(","); + } + + if (!values.isEmpty()) values.setLength(values.length() - 1); + + return values.toString(); + } + + private String getColumnsFromField(Class clazz) { + StringBuilder keys = new StringBuilder(); + + for (Field field : clazz.getDeclaredFields()) { + field.setAccessible(true); + Column column = field.getAnnotation(Column.class); + if (column == null) continue; + String dbName = getDbName(field, column); + keys.append(dbName).append(","); + } + + if (!keys.isEmpty()) keys.setLength(keys.length() - 1); + + return keys.toString(); + } + /** * Processes the value of a field for inclusion in an SQL script. *