# 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<ProductCategory> {

@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.
In DDD, an aggregate is composed of a root entity (the Product) and one or more child entities (the ProductCategory).
Business logic that creates an aggregate is usually put into a Factory. The factory implementation would then be one that calls into the ProductCategoryRepository. That is, the setCategory method (or similar) would belong to the ProductFactory class.