Support user-defined key type in JDBC KeyHolder

Prior to this commit, the JDBC KeyHolder API only supported keys of
type Number. However, a generated key can be a UUID or something else,
and developers shouldn't have to go manually through complex
collections to access it.

This commit adds a new getKeyAs(Class<T> keyType) method to the
KeyHolder API that allows the user to specify the key type.

Closes gh-24655
This commit is contained in:
eXsio
2020-06-16 08:40:59 +02:00
committed by Sam Brannen
parent b572f7618f
commit b50cf9dad2
3 changed files with 52 additions and 5 deletions

View File

@@ -51,13 +51,38 @@ public class KeyHolderTests {
assertThat(kh.getKey().intValue()).as("single key should be returned").isEqualTo(1);
}
@Test
public void singleKeyAsString() {
kh.getKeyList().addAll(singletonList(singletonMap("key", "1")));
assertThat(kh.getKeyAs(String.class)).as("single key should be returned").isEqualTo("1");
}
@Test
public void singleKeyAsWrongClass() {
kh.getKeyList().addAll(singletonList(singletonMap("key", "1")));
assertThatExceptionOfType(DataRetrievalFailureException.class).isThrownBy(() ->
kh.getKeyAs(Integer.class))
.withMessageStartingWith("The generated key is not of a supported type.");
}
@Test
public void singleKeyWithNullValue() {
kh.getKeyList().addAll(singletonList(singletonMap("key", null)));
assertThatExceptionOfType(DataRetrievalFailureException.class).isThrownBy(() ->
kh.getKeyAs(Integer.class))
.withMessageStartingWith("The generated key is not of a supported type.");
}
@Test
public void singleKeyNonNumeric() {
kh.getKeyList().addAll(singletonList(singletonMap("key", "1")));
assertThatExceptionOfType(DataRetrievalFailureException.class).isThrownBy(() ->
kh.getKey().intValue())
.withMessageStartingWith("The generated key is not of a supported numeric type.");
.withMessageStartingWith("The generated key is not of a supported type.");
}
@Test