1.DDD and Spring Data
DDD: domain-driven design is the implementation method of software development under complex requirements. I will explain DDD specifically when I have time.
Spring Data is designed in many places according to the DDD principle (such as Repository). Here Spring Data mainly implements DDD's aggregate and domain event:
Below we demonstrate a statistical number of male and female numbers when Person's aggregate root is saved successfully, through Person's gender attribute, the statistical entity GenderStat is updated.
2. Demo
2.1 Person Aggregate Root
As an Aggregate Root, Person has the ability to publish domain event. There are two ways to implement it under Spring Data:
like:
@Entity@Data@AllArgsConstructor@NoArgsConstructor@ToString(exclude = "domainEvents")public class Person { @Id @GeneratedValue private Long id; private String name; private Integer gender;//1:male;2:female @DomainEvents Collection<Object> domainEvents() { List<Object> events= new ArrayList<Object>(); events.add(new PersonSavedEvent(this.id,this.gender)); return events; } @AfterDomainEventPublication void callbackMethod() { // }}or
@Entity@Data@AllArgsConstructor@NoArgsConstructor@ToString(exclude = "domainEvents")public class Person extends AbstractAggregateRoot{ @Id @GeneratedValue private Long id; private String name; private Integer gender;//1:male;2:female public Person afterPersonSavedCompleted(){ registerEvent(new PersonSavedEvent(this.id, this.gender)); return this; }}2.2 Listening event handling
@Componentpublic class GenderStatProcessor { @Autowired GenderRepository genderRepository; @Async @TransactionalEventListener public void handleAfterPersonSavedComplete(PersonSavedEvent event){ GenderStat genderStat = genderRepository.findOne(1l); if(event.getGender()==1){ genderStat.setMaleCount(genderStat.getMaleCount()+1); }else { genderStat.setFemaleCount(genderStat.getFemaleCount()+1); } genderRepository.save(genderStat); }} 3 Source code address : https://github.com/wiselyman/spring-data-domain-event
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.