Skip to content

Commit

Permalink
Add JsonbSetColumnMapperFactory
Browse files Browse the repository at this point in the history
  • Loading branch information
daforster committed Oct 23, 2023
1 parent 36aac7c commit 2faca3f
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
4 changes: 4 additions & 0 deletions dc-commons-jdbi/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)

## [Unreleased]

### Added

- `JsonbSetColumnMapperFactory` for JSONB columns that contain a set (just an array in JSON though)

## [7.0.3](https://github.com/dbmdz/digitalcollections-commons/releases/tag/dc-commons-jdbi-7.0.3) - 2023-09-15

### Changed
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package de.digitalcollections.commons.jdbi;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Optional;
import java.util.Set;
import org.jdbi.v3.core.config.ConfigRegistry;
import org.jdbi.v3.core.mapper.ColumnMapper;
import org.jdbi.v3.core.mapper.ColumnMapperFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JsonbSetColumnMapperFactory<T> implements ColumnMapperFactory {

private static final Logger LOGGER = LoggerFactory.getLogger(JsonbSetColumnMapperFactory.class);

private final Class clz;
private final ObjectMapper objectMapper;

public JsonbSetColumnMapperFactory(Class<T> clz, ObjectMapper objectMapper) {
this.clz = clz;
this.objectMapper = objectMapper;
}

@Override
@SuppressWarnings("unchecked")
public Optional<ColumnMapper<?>> build(Type type, ConfigRegistry config) {
if (!(type instanceof ParameterizedType)) {
return Optional.empty();
}

Type listType = ((ParameterizedType) type).getActualTypeArguments()[0];
if (!clz.equals(listType)) {
return Optional.empty();
}
return Optional.of(
(r, i, c) -> {
String jsonb = r.getString(i);
if (jsonb == null) {
return null;
}
/* see https://stackoverflow.com/a/11681540 */
try {
JavaType javaType =
objectMapper.getTypeFactory().constructParametricType(Set.class, (Class) listType);

return objectMapper.readValue(jsonb, javaType);
} catch (IOException ex) {
ex.printStackTrace();
LOGGER.error("Error deserializing JSON", ex);
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
});
}
}

0 comments on commit 2faca3f

Please sign in to comment.