DDD and batch processing (e.g. using Spring batch)

对着背影说爱祢 提交于 2021-02-11 01:14:47

问题


I would like to use Spring batch for a batch application. I already have a domain model designed following DDD. My question is how batch processing (in my case, using Spring batch) fits with DDD?

For example, I have an aggregate root A and one of its children is the entity B. A has a list of one or more Bs. The batch application receives a file when each line corresponds to an operation (add, delete...) on the list of Bs. In my aggregate root A, I have one method for each operation (e.g. addB, delB...). Using Spring batch, which ItemWriter should I use? I don't think a JdbcBatchItemWriter is appropriated since I should deal with the data only through the domain. Are there best practices concerning the use of DDD with batch processing?

Thanks


回答1:


I don't pretend to know what exactly the best practice for this is, but this is how I'd do it, considering your design goals. Instead of A and B, say we have a File object, your aggregate, which contains many lines:

class File {
    public void addLine(Line l) {/* implementation here*/}
    public void removeLine(Line l) {/* implementation here*/}
}

class Line {
}

Have your Reader/Processors return LineOperations, encapsulating your line (which you just read) and whether you are doing an add/remove/other:

interface LineOperation {
    public void execute(File file);
}

class DeleteOperation implements LineOperation {

    private Line line;

    private DeleteOperation(Line line) {
        super();
        this.line = line;
    }

    public void execute(File file) {
        file.removeLine(line);
    }
}

Implementations of the AddOperation and whatever else you may require are left to the imagination.

Next, we'll be passing the the LineOperations to your writer. Your writer performs the operation on the Aggregate File, and then uses the FileRepository to write the aggregate.

class LineOperationWriter implements ItemWriter<LineOperation>, StepExecutionListener {

    @Autowired;
    FileRepository fileRepo;

    private Long fileId;

    public void write(List<? extends LineOperation> items) throws Exception {

        File file = fileRepo.find(fileId);
        for (LineOperation lineOperation : items) {
            lineOperation.execute(file);
        }
        fileRepo.persist(file);

    }

    @Override
    public void beforeStep(StepExecution stepExecution) {
        this.fileId = (Long) stepExecution.getJobExecution().getExecutionContext().get("fileId");
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        return null;
    }
}

Hope this helps.



来源:https://stackoverflow.com/questions/10172747/ddd-and-batch-processing-e-g-using-spring-batch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!