如何使用DDD定义具有翻译的实体

时间:2017-11-28 17:24:56

标签: spring-boot domain-driven-design ddd-repositories ddd-service

我有一个使用Domain Driven Design的小应用程序,现在我希望有一个翻译实体。

我在互联网上看到,域驱动设计的最佳实践是将翻译与模型分开,但我不知道该怎么做。

这是我所拥有的一个例子:

@Entity
class Product {
    @Id
    private String id;
    private String name;
    private String description;
    private BigDecimal price;
    private BigDecimal originalPrice;

    ...
}

@Service
class ProductService {

    @Autowired
    private ProductRepository productRepository;

    public List<Product> getAll() {
        return productRepository.findAll();
    }

    public List<Product> getById(String id) {
        return productRepository.findById(id);
    }

    public List<Product> create(ProductDto productDto) {
        Product product = new Product(
            productDto.getName(),
            productDto.getDescription(),
            productDto.getPrice(),
            productDto.getOriginalPrice()
        );
        return productRepository.save(product);
    }
}

然后我的问题是:

想象一下,我正在收到产品DTO中的翻译,我想知道该怎么做。

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

这不是您的核心域名真正感兴趣的内容,您应该对其进行建模。您可能会有一些翻译子域, 会对这些事情感兴趣,但该设计将专注于将键/语言对映射到翻译。

您的核心域名将使用您所在位置的某种默认语言,这将是核心域中众所周知且必需的条目。例如,您的Product可能有ProductID(或SKU或类似内容)以及Description。该描述将采用默认语言。

您的翻译将作为更多基础结构服务在集成层上进行翻译,如果有可用翻译,则会提供已翻译的描述;否则是您域中应该要求的默认值。

<强>更新

我给出的另一个答案DDD: DTO usage with different logic

例如(广泛地):

public Translation 
{
    string Locale { get; set; }
    string Value { get; set; }
}

public interface ILocalisationQuery
{
    Translation For(string locale, string key);
    IEnumerable<Translation> For(string key);
}

public class LocalisationQuery : ILocalisationQuery
{
    public Translation For(string locale, string key)
    {
        // lookup from localisation data store
    }

    public IEnumerable<Translation> For(string key)
    {
        // lookup from localisation data store
    }
}

您实施的策略对您有意义并适用于您的用例。假设您想要获取spoon产品的Fench说明,并且您已使用product-spoon作为密钥的约定:localisation.For('fr', 'product-spoon');

对于我的JavaScript前端,我使用i18next

答案 1 :(得分:0)

我建议您将域模型与数据模型区分开来。在您的域模型中,您真的不关心任何翻译,它看起来就像您提出的那样,您的数据模型可能看起来不同:

@Entity
class Product {
    @Id
    private String id;
    private BigDecimal price;
    private BigDecimal originalPrice;
    private List<ProductTranslation> translations;

    ...
}

@Entity
class ProductTranslation{
    @Id
    private String id;
    private String name;
    private String description;
    private Int languageId;

    ...
}

然后,在您的存储库中,您将从您的域模型映射到数据模型,而您将从某些应用程序设置中获取languageId