If your table has fields that will not be queried but need to be displayed in the UI, it makes sense to save it this way instead of keeping it in a child table. You avoid making extra database queries
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import java.util.List;
@Converter
public class JsonArrayConverter<T> implements AttributeConverter<List<T>, String> {
private final ObjectMapper objectMapper = new ObjectMapper();
@Override
public String convertToDatabaseColumn(List<T> attribute) {
if (attribute == null) {
return null;
}
try {
return objectMapper.writeValueAsString(attribute);
} catch (Exception e) {
throw new RuntimeException("JSON serialization error", e);
}
}
@Override
public List<T> convertToEntityAttribute(String dbData) {
if (dbData == null || dbData.isEmpty()) {
return null;
}
try {
return objectMapper.readValue(dbData, objectMapper.getTypeFactory().constructCollectionType(List.class, getEntityClass()));
} catch (Exception e) {
throw new RuntimeException("JSON deserialization error", e);
}
}
protected Class<T> getEntityClass() {
throw new UnsupportedOperationException("getEntityClass() must be implemented");
}
}
This is how I have a generic class.
public record PersonDetail(String name, Integer degree) {
}
Let's assume we have such an example class(PersonDetail).
import jakarta.persistence.Converter;
@Converter
public class PersonDetailConverter extends JsonArrayConverter<PersonDetail> {
@Override
protected Class<PersonDetail> getEntityClass() {
return PersonDetail.class;
}
}
This is how I have converter classes.
@Column(name = "Detail", columnDefinition = "CLOB")
@Convert(converter = PersonDetailConverter.class)
private List<PersonDetail> personDetailList;
I define it like this in my Entity class.In this way, it saves it in the table as CLOB by converting it to a json array. When it is retrieved from the table, it is kept as a list in memory.
CLOBcolumn type and have a look at this question then stackoverflow.com/q/2887362/4636715