{"id":13755894,"url":"https://github.com/meixuesong/aggregate-persistence","last_synced_at":"2026-01-12T09:13:54.207Z","repository":{"id":41197295,"uuid":"209186900","full_name":"meixuesong/aggregate-persistence","owner":"meixuesong","description":null,"archived":false,"fork":false,"pushed_at":"2023-03-31T15:14:51.000Z","size":192,"stargazers_count":201,"open_issues_count":2,"forks_count":60,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-07-20T17:19:40.839Z","etag":null,"topics":["aggregate","aggregate-persistence","ddd"],"latest_commit_sha":null,"homepage":null,"language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/meixuesong.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2019-09-18T01:08:10.000Z","updated_at":"2025-05-19T02:04:19.000Z","dependencies_parsed_at":"2024-01-30T04:03:18.190Z","dependency_job_id":null,"html_url":"https://github.com/meixuesong/aggregate-persistence","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/meixuesong/aggregate-persistence","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/meixuesong%2Faggregate-persistence","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/meixuesong%2Faggregate-persistence/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/meixuesong%2Faggregate-persistence/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/meixuesong%2Faggregate-persistence/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/meixuesong","download_url":"https://codeload.github.com/meixuesong/aggregate-persistence/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/meixuesong%2Faggregate-persistence/sbom","scorecard":{"id":635649,"data":{"date":"2025-08-11","repo":{"name":"github.com/meixuesong/aggregate-persistence","commit":"b325ab00393073e7422ee79815dfc4c45350051d"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":2.8,"checks":[{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Token-Permissions","score":-1,"reason":"No tokens found","details":null,"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"Pinned-Dependencies","score":-1,"reason":"no dependencies found","details":null,"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"Code-Review","score":0,"reason":"Found 1/17 approved changesets -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Maintained","score":1,"reason":"2 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 1","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Dangerous-Workflow","score":-1,"reason":"no workflows found","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"License","score":10,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Info: FSF or OSI recognized license: Apache License 2.0: LICENSE:0"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":0,"reason":"branch protection not enabled on development/release branches","details":["Warn: branch protection not enabled for branch 'master'"],"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"SAST","score":0,"reason":"SAST tool is not run on all commits -- score normalized to 0","details":["Warn: 0 commits out of 14 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}},{"name":"Vulnerabilities","score":7,"reason":"3 existing vulnerabilities detected","details":["Warn: Project is vulnerable to: GHSA-h46c-h94j-95f3","Warn: Project is vulnerable to: GHSA-jjjh-jjxp-wpff","Warn: Project is vulnerable to: GHSA-j288-q9x7-2f5v"],"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}}]},"last_synced_at":"2025-08-21T09:05:39.991Z","repository_id":41197295,"created_at":"2025-08-21T09:05:39.991Z","updated_at":"2025-08-21T09:05:39.991Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28337656,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-12T06:09:07.588Z","status":"ssl_error","status_checked_at":"2026-01-12T06:05:18.301Z","response_time":98,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aggregate","aggregate-persistence","ddd"],"created_at":"2024-08-03T11:00:32.292Z","updated_at":"2026-01-12T09:13:54.201Z","avatar_url":"https://github.com/meixuesong.png","language":"Java","funding_links":[],"categories":["框架"],"sub_categories":[],"readme":"# Aggregate Persistence\n\n![](https://travis-ci.com/meixuesong/aggregate-persistence.svg?branch=master)\n\n可参考：\n* [DDD之聚合持久化应该怎么做？](https://zhuanlan.zhihu.com/p/334344752)\n* [聊一聊聚合的持久化](https://zhuanlan.zhihu.com/p/87074950) \n\n## 1. 简介\n领域驱动设计(DDD)已经被业界认为是行之有效的复杂问题解决之道。随着微服务的流行，DDD也被更多的团队采纳。然而在DDD落地时，聚合(Aggregate)的持久化一直缺少一种优雅的方式解决。\n\n在DDD实践中，聚合应该作为一个完整的单元进行读取和持久化，以确保业务的不变性或者说业务规则不变破坏。例如，订单总金额应该与订单明细金额之和一致。\n\n由于领域模型和数据库的数据模型可能不一致，并且聚合可能涉及多个实体，因此Hibernate, MyBatis和Spring Data等框架直接用于聚合持久化时，总是面临一些困难，而且代码也不够优雅。有人认为NoSQL是最适合聚合持久化的方案。确实如此，每个聚合实例就是一个文档，NoSQL天然为聚合持久化提供了很好的支持。然而并不是所有系统都适合用NoSQL。当遇到关系型数据库时，一种方式是将领域事件引入持久化过程。也就是在处理业务过程中，聚合抛出领域事件，Repository根据领域事件的不同，执行不同的SQL，完成数据库的修改。但这样的话，Repository层就要引入一些逻辑判断，代码冗余增加了维护成本。\n\n本项目旨在提供一种轻量级聚合持久化方案，帮助开发者真正从业务出发设计领域模型，不需要考虑持久化的事情。在实现Repository持久化时，不需要考虑业务逻辑，只负责聚合的持久化，从而真正做到关注点分离。**也就是说，不论有多少个业务场景对聚合进行了修改，对聚合的持久化只需要一个方法。**\n\n方案的核心是`Aggregate\u003cT\u003e`容器，T是聚合根的类型。Repository以`Aggregate\u003cT\u003e`为核心，当Repository查询或保存聚合时，返回的不是聚合本身，而是聚合容器`Aggregate\u003cT\u003e`。以订单付款为例，Application Service的代码如下：\n\n```java\n@Transactional\npublic void checkout(String orderId, CheckoutRequest request) {\n    Aggregate\u003cOrder\u003e aggregate = orderRepository.findById(orderId);\n    Order order = aggregate.getRoot();\n\n    Payment payment = new Payment(PaymentType.from(request.getPaymentType()), request.getAmount());\n    order.checkout(payment);\n\n    orderRepository.save(aggregate);\n}\n```\n\n`Aggregate\u003cT\u003e`保留了聚合的历史快照，因此在Repository保存聚合时，就可以与快照进行对比，找到需要修改的实体和字段，然后完成持久化工作。它提供以下功能：\n* `public R getRoot()`：获取聚合根\n* `public R getRootSnapshot()`: 获取聚合根的历史快照\n* `public boolean isChanged()`: 聚合是否发生了变化\n* `public boolean isNew()`：是否为新的聚合\n* `public \u003cT\u003e Collection\u003cT\u003e findNewEntitiesById(Function\u003cR, Collection\u003cT\u003e\u003e getCollection, Function\u003cT, ID\u003e getId)`：在实体集合（例如订单的所有订单明细行中）找到新的实体\n* `public \u003cT, ID\u003e Collection\u003cT\u003e findChangedEntities(Function\u003cR, Collection\u003cT\u003e\u003e getCollection, Function\u003cT, ID\u003e getId)`：在实体集合（例如所有订单明细行中）找到发生变更的实体\n* `public \u003cT, ID\u003e Collection\u003cT\u003e findRemovedEntities(Function\u003cR, Collection\u003cT\u003e\u003e getCollection, Function\u003cT, ID\u003e getId)`：在实体集合（例如所有订单明细行中）找到已经删除的实体\n\n工具类`DataObjectUtils`提供了对象的对比功能。它可以帮助你修改数据库时只update那些变化了的字段。以Person为例，`DataObjectUtils.getChangedFields(personSnapshot, personCurrent)`将返回哪些Field发生了变化。你可以据此按需修改数据库（请参考示例工程）。\n\n与Hibernate的`@Version`类似，聚合根需要实现Versionable接口，以便Repository基于Version实现乐观锁。Repository对聚合的所有持久化操作，都要判断Version。示意SQL如下：\n\n```sql\n    insert into person (id, name, age, address, version )\n    values (#{id}, #{name}, #{age}, #{address}, 1)\n\n    update person set age = #{age}, address = #{address}, version = version + 1\n    where id = #{id} and version = #{version}\n    \n    delete person\n    where id = #{id} and version = #{version}\n``` \n\n## 2. 使用Aggregate-Persistence\n\n在项目中加入以下依赖，就可以使用Aggregate-persistence的功能了：\n\n```xml\n        \u003cdependency\u003e\n            \u003cgroupId\u003ecom.github.meixuesong\u003c/groupId\u003e\n            \u003cartifactId\u003eaggregate-persistence\u003c/artifactId\u003e\n            \u003cversion\u003e1.2.1\u003c/version\u003e\n        \u003c/dependency\u003e\n```\n\n## 3. 使用示例\nAggregate-Persistence本身并不负责持久化工作，它是一个工具，用于识别聚合的变更，例如发现有新增、修改和删除的实体，真正的持久化工作由你的Repository实现。\n\n接下来我们通过[订单聚合持久化项目](https://github.com/meixuesong/aggregate-persistence-sample)展示Repository如何利用Aggregate-Persistence的功能，实现订单聚合的持久化。该项目的技术栈使用Springboot, MyBatis。\n\n订单聚合包括两个实体：订单（Order）和订单明细行（OrderItem），其中订单是聚合根：\n\n```java\npublic class Order implements Versionable {\n    private String id;\n    private Date createTime;\n    private Customer customer;\n    private List\u003cOrderItem\u003e items;\n    private OrderStatus status;\n    private BigDecimal totalPrice;\n    private BigDecimal totalPayment;\n    private int version;\n}\n\npublic class OrderItem {\n    private Long id;\n    private Product product;\n    private BigDecimal amount;\n    private BigDecimal subTotal;\n}\n```\n\nOrderRepository完成订单的持久化工作，主要方法如下：\n\n```java\npublic class OrderRepository {\n    Aggregate\u003cOrder\u003e findById(String orderId);\n    void save(Aggregate\u003cOrder\u003e orderAggregate);\n    void remove(Aggregate\u003cOrder\u003e orderAggregate);\n}\n```\n\n在本例中，OrderRepository需要完成订单的新增、订单项的修改（如购买数量变化或者移除了某个商品）、订单的删除功能。由于领域模型与数据模型不一致，因此保存时，Repository将Domain model(Order)转换成Data object(OrderDO)，然后使用MyBatis完成持久化。查询时，进行反向操作，将Data object转换成Domain model.\n\n### 3.1 查询订单\n下面的代码用于查询订单，并返回`Aggregate\u003cOrder\u003e`。当查询数据库并创建Order聚合后，调用`AggregateFactory.createAggregate`创建`Aggregate\u003cT\u003e`对象，在`Aggregate\u003cT\u003e`内部，它将自动保存Order的快照，以供后续对比。\n\n```java\npublic Aggregate\u003cOrder\u003e findById(String id) {\n    OrderDO orderDO = orderMapper.selectByPrimaryKey(id);\n    if (orderDO == null) {\n        throw new EntityNotFoundException(\"Order(\" + id + \") not found\");\n    }\n\n    Order order = orderDO.toOrder();\n    order.setCustomer(customerRepository.findById(orderDO.getCustomerId()));\n    order.setItems(getOrderItems(id));\n\n    return AggregateFactory.createAggregate(order);\n}\n```\n\n### 3.2 保存新增订单、修改订单\n\n使用`save`接口方法完成订单及订单明细行的新增、修改和删除操作。示例代码如下：\n\n```java\nvoid save(Aggregate\u003cOrder\u003e orderAggregate) {\n    if (orderAggregate.isNew()) {\n        //insert order\n        Order order = orderAggregate.getRoot();\n        orderMapper.insert(new OrderDO(order));\n        //insert order items\n        List\u003cOrderItemDO\u003e itemDOs = order.getItems().stream()\n            .map(item -\u003e new OrderItemDO(order.getId(), item))\n            .collect(Collectors.toList());\n        orderItemMapper.insertAll(itemDOs);\n    } else if (orderAggregate.isChanged()) {\n        //update order \n        updateAggregateRoot(orderAggregate);\n        //delete the removed order items from DB\n        removeOrderItems(orderAggregate);\n        //update the changed order items\n        updateOrderItems(orderAggregate);\n        //insert the new order items into DB\n        insertOrderItems(orderAggregate);\n    }\n}\n```\n\n上例代码中，当`orderAggregate.isNew()`为true时，调用MyBatis Mapper插入数据。否则如果聚合已经被修改，则需要更新数据。\n\n首先更新聚合根。领域对象(Order)首先被转换成数据对象（OrderDO），然后DataObjectUtils对比OrderDO的历史版本，得到Delta值，最终调用MyBatis的update selective方法更新到数据库中。代码如下：\n\n```java\nprivate void updateAggregateRoot(Aggregate\u003cOrder\u003e orderAggregate) {\n    //only update changed fields, avoid update all fields\n    OrderDO newOrderDO = new OrderDO(orderAggregate.getRoot());\n    Set\u003cString\u003e changedFields = DataObjectUtils.getChangedFields(orderAggregate.getRootSnapshot(), orderAggregate.getRoot());\n    if (orderMapper.updateByPrimaryKeySelective(newOrderDO, changedFields) != 1) {\n        throw new OptimisticLockException(String.format(\"Update order (%s) error, it's not found or changed by another user\",\n                orderAggregate.getRoot().getId()));\n    }\n}\n```\n\n对于订单明细行的增删改，都是通过Aggregate找到新增、删除和修改的实体，然后完成数据库操作。代码示例如下：\n\n```java\nprivate void removeOrderItems(Aggregate\u003cOrder\u003e orderAggregate) {\n    Collection\u003cOrderItem\u003e removedEntities = orderAggregate.findRemovedEntities(Order::getItems, OrderItem::getId);\n    removedEntities.stream().forEach((item) -\u003e {\n        if (orderItemMapper.deleteByPrimaryKey(item.getId()) != 1) {\n            throw new OptimisticLockException(String.format(\"Delete order item (%d) error, it's not found\", item.getId()));\n        }\n    });\n}\n\nprivate void updateOrderItems(Aggregate\u003cOrder\u003e orderAggregate) {\n    Collection\u003cChangedEntity\u003cOrderItem\u003e\u003e entityPairs = orderAggregate.findChangedEntitiesWithOldValues(Order::getItems, OrderItem::getId);\n    for (ChangedEntity\u003cOrderItem\u003e pair : entityPairs) {\n        Set\u003cString\u003e changedFields = DataObjectUtils.getChangedFields(pair.getOldEntity(), pair.getNewEntity());\n        OrderItemDO orderItemDO = new OrderItemDO(orderAggregate.getRoot().getId(), pair.getNewEntity());\n        if (orderItemMapper.updateByPrimaryKeySelective(orderItemDO, changedFields) != 1) {\n            throw new OptimisticLockException(String.format(\"Update order item (%d) error, it's not found\", orderItemDO.getId()));\n        }\n    }\n}\n\nprivate void insertOrderItems(Aggregate\u003cOrder\u003e orderAggregate) {\n    Collection\u003cOrderItem\u003e newEntities = orderAggregate.findNewEntities(Order::getItems, (item) -\u003e item.getId() == null);\n    if (newEntities.size() \u003e 0) {\n        List\u003cOrderItemDO\u003e itemDOs = newEntities.stream().map(item -\u003e new OrderItemDO(orderAggregate.getRoot().getId(), item)).collect(Collectors.toList());\n        orderItemMapper.insertAll(itemDOs);\n    }\n}\n```\n\n`Aggregate\u003cT\u003e`提供的`findXXXEntities`系列方法，都是针对订单明细行这样的实体集合。例如订单明细中，可能增加了商品A，修改了商品B的数量，删除了商品C。`findXXXEntities`方法用于找出这些变更。第1个参数是函数式接口，用于获取实体集合，以便在此集合中识别新增、修改和删除的实体。第2个参数也是函数式接口，获得实体主键值。\n\n需要提醒的是，当聚合发生变化时，不论聚合根是否发生变化，都应该修改聚合根的版本号，以确保聚合作为一个整体被修改，避免并发修改时产生的数据不一致现象。\n\n### 3.3 删除订单\n\n删除订单的同时，需要删除所有订单明细行。\n\n```java\npublic void remove(Aggregate\u003cOrder\u003e aggregate) {\n    Order order = aggregate.getRoot();\n    if (orderMapper.delete(new OrderDO(order)) != 1) {\n        throw new OptimisticLockException(\n            String.format(\"Delete order (%s) error, it's not found or changed by another user\", order.getId())\n        );\n    }\n    orderItemMapper.deleteByOrderId(order.getId());\n}\n```\n\n完整的示例代码见[订单聚合持久化项目](https://github.com/meixuesong/aggregate-persistence-sample)，该示例演示了如何运用Mybatis实现聚合的持久化，并且只持久化那些修改的数据。例如一个表有20个字段，只有1个字段修改了，采用此方案时，只会修改数据库的一个字段，而非所有字段。\n\n## 4. 总结\n总的来说，本项目提供了一种轻量级聚合持久化方案，能够帮助开发者设计干净的领域模型的同时，很好地支持Repository做持久化工作。通过持有聚合根的快照，`Aggregate\u003cT\u003e`可以识别聚合发生了哪些变化，然后Repository使用基于Version的乐观锁和DataObjectUtils在字段属性级别的比较功能，实现按需更新数据库。\n\n## 5. Changelog\n1.2 修改了之前采用对比字段值，如果为null时判断为未修改的方式。新方式改为使用`DataObjectUtils.getChangedFields`获取变更的字段名。\n\n1.3 直接依赖做 ![DeepEquals](https://github.com/jdereg/java-util) 比较。","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmeixuesong%2Faggregate-persistence","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmeixuesong%2Faggregate-persistence","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmeixuesong%2Faggregate-persistence/lists"}