Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support getGeneratedKeys returns 1 key for multi-row insert #24

Merged
merged 1 commit into from
Oct 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 31 additions & 4 deletions code/src/main/java/org/jacuzzi/core/GenericDaoImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import javax.sql.DataSource;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
Expand Down Expand Up @@ -277,14 +278,40 @@ public void insert(List<T> objects) {
}
}
} else {
throw new DatabaseException(
"Unexpected number of rows with generated keys: " + generatedKeys.size() + " instead of " +
objects.size() + '.'
);
if (generatedKeys.size() == 1) {
Collection<Object> keys = result.getGeneratedKeysForRow(0).values();

if (keys.size() == 1) {
Object key = keys.iterator().next();
for (T object : objects) {
typeOracle.setIdValue(object, key);
key = increaseKey(key);
}
}
} else {
throw new DatabaseException("Unexpected number of rows with generated keys: "
+ generatedKeys.size() + " instead of " + objects.size() + '.');
}
}
}
}

private Object increaseKey(Object key) {
if (key instanceof Long) {
return (Long) key + 1;
} else if (key instanceof Integer) {
return (Integer) key + 1;
} else if (key instanceof Short) {
return (Short) key + 1;
} else if (key instanceof Byte) {
return (Byte) key + 1;
} else if (key instanceof BigInteger) {
return ((BigInteger) key).add(BigInteger.ONE);
}

throw new DatabaseException("Can't increase key of type " + key.getClass().getName() + '.');
}

@Override
public void update(T object) {
if (object == null) {
Expand Down
Loading