Converter HashMapy do zapisu json'a w bazie danych

0

Hej, chce napisać konwerter do HashMapy, który będzie użyty w encji na atrybucie i przemapuje mape na pole które będzie jsonem (stringiem) w bazie danych. Proszę o pomoc.

@Converter
@ApplicationScoped
@Slf4j
@Traced
@RequiredArgsConstructor
public class PropertiesConverter implements AttributeConverter<Map<String, String>, String> {

    private final ObjectMapper mapper;

    @Override
    public String convertToDatabaseColumn(Map<String, String> properties) {
        try {
            return mapper.writeValueAsString(properties);
        } catch (JsonProcessingException e) {
            log.error("Conversion from object to JSON failed");
            throw new ArrayIndexOutOfBoundsException();
        }
    }

    @Override
    public Map<String, String> convertToEntityAttribute(String propertiesAsJson) {
        try {
            return mapper.readValue(propertiesAsJson, new TypeReference<>() {
            });
        } catch (JsonProcessingException e) {
            log.error("Conversion from JSON to object failed");
            throw new ArrayIndexOutOfBoundsException("conversion from JSON to object failed");
        }
    }
}
@Table(name = "cars")
public class CarEntity {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @EqualsAndHashCode.Include
    private Long id;

    private String description;

    @Convert(converter = PropertiesConverter.class)
    @NotEmpty
    @Setter(NONE)
    @ElementCollection
    Map<String, String> properties = new HashMap<>();

plus dodaje pole w skrypcie liquidbase

        <addColumn tableName="cars">
            <column name="properties" type="varchar(255)"/>
        </addColumn>
0

tak, leci błąd z liquidbase przy odpalaniu aplikacji, dodatkowo tak teraz myśle, że nie chciałbym używać @ElementCollection bo to stworzy mi osobną tabelke, a ja chce mieć to w tej samej tabelce w osobnej kulumnie.
Może dobrym pomysłem będzie tu np. zamiast Mapy użyć Liste obiektów z argumentami key i value ?

1

Skoro i tak dajesz do Stringa mapper.writeValueAsString(properties); to czemu nie mieć tego pola w bazie i w encji jako zwykły String?

EDIT:
Wtedy miałbyś dodatkową metodę np retrieveProperties() która w środku by sobie konwertowała Stringa na mape.

1 użytkowników online, w tym zalogowanych: 0, gości: 1