I have such task: in spring/hibernate/postgres I have a entity(aggregate) that contains jsonb with children codes. Like in a container can be 100 blocks of sigarets, every one contains 10 packs and all of them (all 3 level) everyone have a uniqe code and located in one DB table.
@Entity
@Table(name = "code")
@Getter
@Setter
@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
public class CodeDO {
@Id
private String code;
private String status;
private String type;
@Type(type = "jsonb")
@Column(columnDefinition = "jsonb")
private JsonNode children; // contains {code1, code2, code3}
}
I need to write HQL or SQL query to get Jsonb and for every element(child) SELECT * FROM code. Only for children 1 level down. Now I have something like that:
@RequiredArgsConstructor
@Service
public class CodeServiceImpl implements CodeService {
private final CodeRepository codeRepository;
public List<List> getCodeFromAggregateChildren(String id, KmListRequest req) {
JsonNode jsonNode = codeRepository.getById(id).getChildren();
List<String> idList = new ObjectMapper().convertValue(jsonNode, List.class);
List<JsonNode> childNodes= idList.forEach(childId -> codeRepository.getById(childId));
return childNodes.stream().map(child -> new ObjectMapper().convertValue(child, List.class)).collect(Collectors.toList());
}
}
So it works like 2 queries. First: get children, second: select for every children. The task is not to touch DB twice, combine this 2 queries in one.