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?