Check repository for a nested entity I have a Product entity and a ProductCategory entity. Given the Product entity, my application checks the database via a repository to see if the ProductCategory already exists. If the category is not found in the database, then the application should persist it.

Currently, I have this code in the service layer as follows:

public class ProductCategoryMapper implements DataMapper&lt;ProductCategory&gt; {

    @NonNull
    private final ProductCategoryRepository categoryRepository;

    @Override
    public void map(Product product) {
        ProductCategory category = productCategoryRepository.findByProductTagAndMake(product);

        if (category == null) {
           category = productCategoryRepository.save(new ProductCategory(product.getTag(), product.getMake()));
        }
        product.setProductCategory(category);
    }
}


But should this method be in the Product class as:

public void mapCategory(); // or perhaps setCategory();


This seems to be better OO but then the Product entity would have a reference to the repository (which I think is bad from a design / DDD perspective b/c the entity knows about repositories). Should the code stay in the service layer, be moved to the entity, or is there some other option?
It appears that this Product entity is meant to be a POJO.  POJOs should be responsible only for holding the relevant data in memory to be accessed by, and possibly manipulated by, someone else.

The second you put in logic that is not directly related to the POJO, such as persistence, the flexibility of your application drops like a stone.  You will be unable to use this POJO in other contexts where the repository will not be relevant, or worse, when this comes from a different repository altogether (it does happen!).