'Recursive DTO in Java

I'm trying to create a DTO from my @Entity called Category, but I'm not able to figure out how to handle recursion in the constructor.

The issue is that in the Category there is an attribute List<Category> subcategories; of subcategories. Here is the table and @Entity snippet of the model:

create table CATEGORY (
    CATEGORY_ID NUMBER not null,
    NAME VARCHAR2(50) not null,
    PARENT_ID NUMBER,
    IMAGE_URL VARCHAR2(256),
    ORDER_NUMBER NUMBER(11)
)
@Entity
@Table(name = "CATEGORY")
public class ProductCategory {
    @Id
    @Column(name = "CATEGORY_ID")
    private Integer id;

    @Column(name = "NAME")
    private String name;

    @JoinColumn(name = "PARENT_ID")
    private Integer parent_id;

    @Column(name = "IMAGE_URL")
    private String imageUrl;

    @Column(name = "ORDER_NUMBER")
    private Integer orderNumber;

    @ManyToOne
    @JoinColumn(name = "PARENT_ID")
    private ProductCategory parent;

    @OneToMany(mappedBy = "parent")
    @OrderBy("orderNumber")
    private List<Category> subcategories;

    @OneToMany(targetEntity = Product.class)
    @JoinColumn(name = "PRODUCT_ID", referencedColumnName = "CATEGORY_ID")
    private List<Product> products;

    // some other attributes and getters and setters
}

What I'm trying to achieve is to convert the entity Category to CategoryDTO, but I struggle with the constructor:

public class CategoryDTO {
    private final Integer categoryId;

    private final String imageUrl;

    private final List<ProductDTO> products;

    private final List<CategoryDTO> subcategories;

    @Inject
    public ProductCategoryDTO(final Category cat) {
        this.categoryId = cat.getId();
        this.imageUrl = cat.getImageUrl();
        this.articles = cat.getArticles()
            .stream()
            .map(Product::new)
            .collect(Collectors.toList());
        this.subcategories = // here I want to call something like this() to convert
                             // subcategories of type Category to CategoryDTO
    }
    // other methods

How can I handle recursion in the constructor of DTO object?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source