Skip to content

Commit

Permalink
Add JsonbSetArgumentFactory
Browse files Browse the repository at this point in the history
  • Loading branch information
daforster committed Oct 26, 2023
1 parent 0c25a9a commit 942a316
Showing 1 changed file with 55 additions and 0 deletions.
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));
}
}

0 comments on commit 942a316

Please sign in to comment.