If we follow DDD principles, one aggregate root should have only references (by id) to another aggregate root(s).
Example:
// Product Aggregate root
class Product {
// References to categories Aggregate Roots (to ids)
Set<Long> categoryIds;
}
But how can it be achieved with JPA/Hibernate? In jpa, if we want to have, for example, OneToMany relation, we defined it as follow:
// Product Aggregate root
class Product {
// Holds category aggregate roots
@OneToMany(mappedBy = "", cascade = CascadeType.ALL)
Set<Category> categories;
}
So JPA-s approach will hold category aggregate roots itself, which is not recommended in DDD.
How would you design relations with JPA but to fit DDD principles?
P.S.: I was thinking to make categories
property of string type and hold comma separated list of category ids, but is there any better solution?
You could use a join table to avoid the categories aggregating the roots like this:
Just as an example I'll plug a few together:
Which results in the following (you didn't specify your DBMS, so I just assumed...) MySQL:
And of course no surprise with respect to their content:
Also I would avoid storing relations in a comma-separated list when you're using a relational database. It leads to unhealthy database design and will cause you headaches at some point.