Search code examples
domain-driven-designddd-repositories

How to Implement DDD repository pattern using raw JDBC or Mybatis?


let's say I have a complex aggregate root (AR)

in a user transaction, I multiple this AR:

ar.doSomeThing1();
ar.doSomething2();
ar.doSomething3();
ar.doSomething4();

then I use a repository to persistent all the change

arRepo.update(ar)

My question is How to Implement arRepo.update use row JDBC or Mybatis?

the main difficulty is :

  1. arRepo does not know what changed, the only way is to update all the ar data in the database.

Solution

  • The main principle is that your DDD core should know nothing about JDBC, TCP or ORM. Everything it knows should be expressed in terms of a Ubiquitous Language.

    But that doesn't mean it shouldn't know what changed. You may use sort of event sourcing and save events under AR from which necessary updates could be derived.

    Maybe that gets not very object-oriented, but you may give it a try. Effectively, AR can be represented as a decision maker, who gets requests for changing its state, decides whether to accept these requests or reject, and then stores a list of state-changing events.

    You then need to reduce this event list to a read model somewhere, but that's not the responsibility of AR, if you use this approach.

    When I mention decision making, I mean a pure function that doesn't go to a disk or a network for data. It means, that all necessary data should be gathered prior to decision making and persisted afterwards. That goes to application layer.

    And this application layer is who interacts with repositories or network adapters. It may also handle transactions and so on. Next, calculating an SQL UPDATE query is an implementation detail of a repository. But as long as a state changes are expressed in terms of ubiquitous language, it can well be known to aggregates and domain core.