DDD: Entity identity before being persisted

后端 未结 5 2136
面向向阳花
面向向阳花 2020-12-25 07:58

In Domain Driven Design, one of the defining characteristic of an Entity is that it has an identity.

Problem:

I am not able to provide a uni

5条回答
  •  春和景丽
    2020-12-25 08:50

    You can use a sequence generator to generate unique int/long identifiers when you instantiate an entity object.

    The interface looks like:

    interface SequenceGenerator {
        long getNextSequence();
    }
    

    A typical implementation of a sequence generator uses a sequence table in the database. The sequence table contains two columns: sequenceName and allocatedSequence.

    When getNextSequence is called first time, it writes a large value (say 100) to the allocatedSequence column and return 1. The next call will return 2 without need to access the database. When the 100 sequences runs out, it reads and increments the allocatedSequence by 100 again.

    Have a look at the SequenceHiLoGenerator in Hibernate source code. It basically does what I described above.

提交回复
热议问题