In the Book "Implementing Domain-Driven Design" the author suggests to implement a repository method to provide the next application-generated (not database-generated) ID. Like so:
class MyRepo {
public MyId nextId() {
return new MyId(UUID.fromRandom());
}
}
That would lead to code like this:
var id = repository.nextId();
var entity = new MyEntity(id, ...);
But although I can see the point that providing IDs is somehow the responsibility of a repository, I don't see an actual benefit of this implementation. Why not assigning the ID directly on object construction?
@Entity
public class MyEntity {
@Id
private MyId id = new MyId(UUID.fromRandom());
}
One could also argue that the identity is a central part of the entity itself.
But apart from this philoshophical difference, I see the benefit of creating the ID directly in the entity that no additional call to the repository is needed.
Do you see any advantage of providing the ID by the repository?