-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
55 changes: 55 additions & 0 deletions
55
...ommons-jdbi/src/main/java/de/digitalcollections/commons/jdbi/JsonbSetArgumentFactory.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package de.digitalcollections.commons.jdbi; | ||
|
||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
import java.io.IOException; | ||
import java.lang.reflect.ParameterizedType; | ||
import java.lang.reflect.Type; | ||
import java.sql.SQLException; | ||
import java.sql.Types; | ||
import java.util.Optional; | ||
import java.util.Set; | ||
import org.jdbi.v3.core.argument.Argument; | ||
import org.jdbi.v3.core.argument.ArgumentFactory; | ||
import org.jdbi.v3.core.argument.NullArgument; | ||
import org.jdbi.v3.core.config.ConfigRegistry; | ||
|
||
public class JsonbSetArgumentFactory<T> implements ArgumentFactory { | ||
|
||
private final Class<T> clz; | ||
private final ObjectMapper objectMapper; | ||
|
||
public JsonbSetArgumentFactory(Class<T> clz, ObjectMapper objectMapper) { | ||
this.clz = clz; | ||
this.objectMapper = objectMapper; | ||
} | ||
|
||
protected Argument build(Set<T> value, ConfigRegistry config) { | ||
return (i, p, cx) -> { | ||
if (value == null) { | ||
p.setNull(i, Types.OTHER); | ||
} else { | ||
try { | ||
p.setString(i, objectMapper.writeValueAsString(value)); | ||
} catch (IOException ex) { | ||
throw new SQLException(ex); | ||
} | ||
} | ||
}; | ||
} | ||
|
||
@Override | ||
@SuppressWarnings("unchecked") | ||
public Optional<Argument> build(Type type, Object value, ConfigRegistry config) { | ||
if (!(type instanceof ParameterizedType)) { | ||
return Optional.empty(); | ||
} | ||
|
||
Type setType = ((ParameterizedType) type).getActualTypeArguments()[0]; | ||
|
||
if (!clz.equals(setType)) { | ||
return Optional.empty(); | ||
} | ||
return Optional.of( | ||
value == null ? new NullArgument(Types.OTHER) : build((Set<T>) value, config)); | ||
} | ||
} |