最近刚解决这个问题就刷到你这个问题
我是 Postgresql 查询的时候把主数据和子数据一次性查询,子数据使用 json 数组作为子数据的一列,然后自定义一个 TypeHandler 将 json 数组转成对象集合;
```java
@
MappedJdbcTypes(value = JdbcType.VARCHAR)
public class CustomListTypeHandler<T> extends AbstractJsonTypeHandler<List<T>> {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final Class<T> elementType;
public CustomListTypeHandler(Class<T> elementType) {
this.elementType = elementType;
}
@
Override protected List<T> parse(String json) {
try {
CollectionType collectiOnType= OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, elementType);
return OBJECT_MAPPER.readValue(json, collectionType);
} catch (JsonProcessingEception e) {
throw new RuntimeException(e);
}
}
@
Override protected String toJson(List<T> obj) {
try {
return OBJECT_MAPPER.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}
```