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>