I'm still studying such pattern (that is CQRS) and a colleague of mine started to implement it in our little project, but frankly I do really have some doubts about its implementation.
For starters we didn't use any particular framework and we developed in Java with Spring Boot (but this question is not programming language specific). Another thing you may find very weird about this is that the pattern has not been implemented completely, just the Command and Query Separation concept (no events, no aggregates, no real bus).
So let's take a look to what we have done, with a bottom-up approach:
I don't want to go much deeper in our implementation, since I just want to know if the following Command is feasible or not.
@Data // Lombok annotation
@Entity
class User {
@Id private Long id;
private String firstName;
private String lastName;
private Integer age;
}
@Value
class EditUserCommand {
private final User user;
}
@Service
class EditUserCommandHandler extends CommandHandler<EditUserCommand> {
@Inject
private UserRepository users;
@Override
public void handle(final EditUserCommand command) {
User old = this.users.findOne(command.getUser().getId());
User current = command.getUser();
current.setId(old.getId());
current = this.users.save(current);
}
}
And this is how we implemented the pattern (or rather the C&Q Separation concept) in our project... but frankly? I don't know if it's right and I found the code quite unconventional for a CQRS pattern. My questions then:
Thanks in advance for any reply.
答案 0 :(得分:6)
你是对的。该命令应该只包含执行实际作业所需的最少信息(在ModifyUserAgeCommand的情况下,它只能包含用户ID和新的年龄)。在您的处理程序中,您的存储库应负责从数据库中重新保护模型,并应用命令中包含的信息中适用的任何更改并与存储库保持一致。如果您正在使用DDD,请使用负责用户的汇总来应用更改并保持不变。
顺便说一句,只要您使用单独的类和模型处理读取(查询)和写入(命令),它仍然是CQRS。 CQRS必须包括事件采购,最终一致性,DDD ......恕我直言,它恰好与这些模式配合得非常好。