Interface Entity<T>

Type Parameters:
T - the type of the entity's state, typically an immutable value object like UserProfile
All Known Subinterfaces:
AggregateRoot<T>
All Known Implementing Classes:
DelegatingEntity, ImmutableAggregateRoot, ImmutableEntity, LazyAggregateRoot, ModifiableAggregateRoot, ModifiableEntity, NoOpEntity, SideEffectFreeEntity

public interface Entity<T>
Represents an entity that encapsulates domain behavior and state. An entity is a core construct of domain modeling and may have a unique identity, a set of attributes, and relationships with other entities. This interface defines the contract for managing an entity's type, identity, lifecycle, relationships, and operations that allow state mutations with event sourcing.
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    static final String
    A constant key used for identifying the aggregate ID in metadata of events.
    static final String
    A constant key used for identifying the sequence number of an applied event in metadata.
    static final String
    A constant key used for identifying the aggregate type in metadata of events.
    static final ThreadLocal<Boolean>
     
    static final ThreadLocal<Boolean>
     
  • Method Summary

    Modifier and Type
    Method
    Description
    Retrieves a collection of aliases associated with this entity.
    default Stream<Entity<?>>
    Retrieves a stream of all entities, including the current entity and all nested entities.
    default List<Entity<?>>
    Retrieves a list of the ancestor entities for the current entity.
    default <A> A
    ancestorValue(Class<A> ancestorType)
    Retrieves the value of the first ancestor entity in the hierarchy that matches the specified type.
    apply(Message eventMessage)
    Applies the given message to the entity.
    default Entity<T>
    Applies the given deserializing message to the entity.
    default Entity<T>
    apply(Object event)
    Processes the given event and applies the corresponding logic based on its type.
    default Entity<T>
    apply(Object... events)
    Applies the given events to reconstruct or update the entity's state.
    default Entity<T>
    apply(Object event, Metadata metadata)
    Applies an event and associated metadata to produce a resulting entity.
    default Entity<T>
    apply(Collection<?> events)
    Applies a collection of events to the current entity, returning an updated entity.
    default Entity<T>
    assertAndApply(Object payloadOrMessage)
    Verifies that the provided update is legal given the current state of the aggregate and on success applies it to the aggregate.
    default Entity<T>
    assertAndApply(Object... updates)
    Applies a number of updates to the current entity after performing necessary legality assertions.
    default Entity<T>
    assertAndApply(Object payload, Metadata metadata)
    Verifies that the provided update is legal given the current state of the aggregate and on success applies it to the aggregate.
    default Entity<T>
    Applies a collection of updates sequentially to the current entity after asserting each is legal, and returns the resulting entity.
    <E extends Exception>
    Entity<T>
    Verifies that the provided update is legal given the current state of the aggregate.
    default Set<Relationship>
    associations(Entity<?> previous)
    Determines the set of new associations (relationships) that are present in the current entity but not in the provided previous entity.
    Commits the current state of the entity, persisting any changes made to it.
    default int
    Calculates the depth level of the current entity in the aggregate.
    default Set<Relationship>
    dissociations(Entity<?> previous)
    Identifies and returns the set of relationships that are dissociated when compared to the relationships of the given previous entity.
    Collection<? extends Entity<?>>
    Retrieves child entities of this entity.
    get()
    Retrieves the current instance of the entity.
    static String
    Retrieves the aggregate ID from the metadata of the given message.
    static Class<?>
    Retrieves the aggregate type from the metadata of the given message.
    default <C> Optional<Entity<C>>
    getEntity(Object entityId)
    Retrieves an entity based on the provided entity ID.
    static Long
    Retrieves the sequence number from the metadata of the given message.
    static boolean
    Determines whether the given message contains a sequence number in its metadata.
    default Long
    Retrieves the highest event index associated with the aggregate.
    id()
    Retrieves the unique identifier of the entity.
    Retrieves the name of the property that serves as the unique identifier for the entity.
    default Entity<T>
    Applies the specified action to this entity if it is present, returning the result of the action.
    static boolean
    Indicates whether any entity is currently being applied to in this thread.
    default boolean
    Checks if the current entity instance is empty.
    static boolean
    Indicates whether any entity is currently being loaded in this thread.
    default boolean
    Checks whether the entity is considered present.
    default boolean
    Determines whether the current entity is the root entity in its hierarchical structure.
    default String
    Retrieves the identifier of the last event applied to the entity hierarchy.
    default Long
    Retrieves the index of the last event applied to this entity hierarchy.
    default <U> Optional<U>
    Maps the entity to a new value if the entity is present.
    Retrieves the parent entity of the current entity.
    default Optional<Entity<T>>
    Plays back through older versions of this entity until a specified condition is met.
    default Entity<T>
    playBackToEvent(Long eventIndex, String eventId)
    Finds a version of this entity matching the given eventIndex or eventId.
    default Iterable<Entity<?>>
    Determines the possible target entities for the given update.
    default Entity<T>
    Retrieves the previous version of this entity.
    default Set<Relationship>
    Retrieves the set of relationships between the aggregate root and all its entities.
    default Entity<?>
    Retrieves the root entity in the hierarchy.
    default Aggregate
    Retrieves the root-level annotation of the aggregate, if any.
    default long
    Retrieves the sequence number of the current entity.
    default Instant
    Retrieves the timestamp of the entity.
    Retrieves the type of the entity.
    update(UnaryOperator<T> function)
    Updates the current entity's value using the specified unary operator and returns a new entity containing the updated value.
    default Entity<T>
    withEventIndex(Long index, String messageId)
    Updates the event index and message ID of the entity and returns the updated version of the entity.
    default Entity<T>
    withSequenceNumber(long sequenceNumber)
    Returns an updated entity based on this with the specified sequence number.
    withType(Class<T> type)
    Sets the type of the entity to the specified class and returns the updated entity.
  • Field Details

    • loading

      static final ThreadLocal<Boolean> loading
    • applying

      static final ThreadLocal<Boolean> applying
    • AGGREGATE_ID_METADATA_KEY

      static final String AGGREGATE_ID_METADATA_KEY
      A constant key used for identifying the aggregate ID in metadata of events. The value associated with this key represents the unique identifier of an aggregate to which the event was applied.
      See Also:
    • AGGREGATE_TYPE_METADATA_KEY

      static final String AGGREGATE_TYPE_METADATA_KEY
      A constant key used for identifying the aggregate type in metadata of events. The value associated with this key represents the type of aggregate to which the event was applied.
      See Also:
    • AGGREGATE_SN_METADATA_KEY

      static final String AGGREGATE_SN_METADATA_KEY
      A constant key used for identifying the sequence number of an applied event in metadata.
      See Also:
  • Method Details

    • isLoading

      static boolean isLoading()
      Indicates whether any entity is currently being loaded in this thread.
      Returns:
      true if any entity is currently being loaded, false otherwise.
    • isApplying

      static boolean isApplying()
      Indicates whether any entity is currently being applied to in this thread.
      Returns:
      true if any entity is currently being applied to, false otherwise.
    • getAggregateId

      static String getAggregateId(HasMetadata message)
      Retrieves the aggregate ID from the metadata of the given message.
      Parameters:
      message - the message containing metadata from which the aggregate ID is retrieved
      Returns:
      the aggregate ID extracted from the metadata, or null if the key is not present
    • getAggregateType

      static Class<?> getAggregateType(HasMetadata message)
      Retrieves the aggregate type from the metadata of the given message.
      Parameters:
      message - the message containing metadata from which the aggregate type is retrieved
      Returns:
      the aggregate type as a Class<?>, or null if the metadata key is not present
    • hasSequenceNumber

      static boolean hasSequenceNumber(HasMetadata message)
      Determines whether the given message contains a sequence number in its metadata.
      Parameters:
      message - the message to check for the presence of a sequence number in its metadata
      Returns:
      true if the metadata contains the key for the sequence number, false otherwise
    • getSequenceNumber

      static Long getSequenceNumber(HasMetadata message)
      Retrieves the sequence number from the metadata of the given message. The sequence number is extracted as a Long if present; otherwise, null is returned.
      Parameters:
      message - the message containing metadata from which the sequence number is retrieved
      Returns:
      the sequence number as a Long, or null if the metadata key is not present or the value cannot be parsed
    • id

      Object id()
      Retrieves the unique identifier of the entity.
      Returns:
      the unique identifier of the entity, or null if this entity has not been initialized yet
    • type

      Class<T> type()
      Retrieves the type of the entity.
      Returns:
      the class type of the entity, or null if the type has not been defined
    • withType

      Entity<T> withType(Class<T> type)
      Sets the type of the entity to the specified class and returns the updated entity.
      Parameters:
      type - the class representing the type to be set for the entity
      Returns:
      the updated entity with the specified type
    • get

      T get()
      Retrieves the current instance of the entity.
      Returns:
      the current instance of the entity or null if not initialized
    • isEmpty

      default boolean isEmpty()
      Checks if the current entity instance is empty.

      This method determines whether the value held by this entity is `null`.

      Returns:
      true if the entity's current instance is null, false otherwise
    • isPresent

      default boolean isPresent()
      Checks whether the entity is considered present.
      Returns:
      true if the current instance of the entity is not null, false otherwise
    • ifPresent

      default Entity<T> ifPresent(UnaryOperator<Entity<T>> action)
      Applies the specified action to this entity if it is present, returning the result of the action. If this entity is not present (i.e., its value is null), the entity itself is returned unchanged.
      Parameters:
      action - the action to apply to this entity if it is present; must be a UnaryOperator that accepts and returns an Entity<T>
      Returns:
      the result of applying the action to this entity if it is present, or this entity itself if it is not present
    • mapIfPresent

      default <U> Optional<U> mapIfPresent(Function<Entity<T>,U> action)
      Maps the entity to a new value if the entity is present. This method applies the provided mapping function to the entity if it is initialized and returns an Optional containing the result or an empty Optional if the entity is not present.
      Type Parameters:
      U - the type of the result of applying the mapping function
      Parameters:
      action - the mapping function to apply to the entity if present
      Returns:
      an Optional containing the result of the mapping function, or an empty Optional if the entity is not present
    • idProperty

      String idProperty()
      Retrieves the name of the property that serves as the unique identifier for the entity.
      Returns:
      the name of the identification property as a string
    • parent

      Entity<?> parent()
      Retrieves the parent entity of the current entity.
      Returns:
      the parent entity of the current entity, or null if this entity does not have a parent
    • ancestors

      default List<Entity<?>> ancestors()
      Retrieves a list of the ancestor entities for the current entity. The ancestors are ordered from the farthest ancestor to the closest parent.
      Returns:
      a list of ancestor entities in hierarchical order, with the root entity first and the closest parent last
    • ancestorValue

      default <A> A ancestorValue(Class<A> ancestorType)
      Retrieves the value of the first ancestor entity in the hierarchy that matches the specified type. The search iterates through the ancestors of the current entity until one of the specified type is found. If no matching ancestor is found, this method returns null.
      Type Parameters:
      A - the type of the ancestor entity to search for
      Parameters:
      ancestorType - the class representing the type of the ancestor entity to find
      Returns:
      the value of the matching ancestor entity cast to the specified type, or null if no such ancestor is found
    • aliases

      Collection<?> aliases()
      Retrieves a collection of aliases associated with this entity.
      Returns:
      a collection containing aliases of this entity, or an empty collection if no aliases are present
    • isRoot

      default boolean isRoot()
      Determines whether the current entity is the root entity in its hierarchical structure.

      This method checks if the entity has no parent, indicating it is at the top level of the hierarchy.

      Returns:
      true if the current entity has no parent and is considered the root entity, false otherwise
    • root

      default Entity<?> root()
      Retrieves the root entity in the hierarchy. The root entity is determined by traversing up the parent hierarchy until a root entity, which has no parent, is found.
      Returns:
      the root entity if a parent hierarchy exists, or this entity itself if no parent is present
    • lastEventId

      default String lastEventId()
      Retrieves the identifier of the last event applied to the entity hierarchy.
      Returns:
      the identifier of the last event as a string, or null if no events have been recorded in the entity's aggregate
    • lastEventIndex

      default Long lastEventIndex()
      Retrieves the index of the last event applied to this entity hierarchy.
      Returns:
      the index of the last event as a Long, or null if no events have been recorded for the entity's aggregate
    • highestEventIndex

      default Long highestEventIndex()
      Retrieves the highest event index associated with the aggregate. The method resolves the lastEventIndex(). If that's null, it recursively checks the last event index of previous versions of the entity. Returns null if no version of this entity has an event index.
      Returns:
      the highest event index as a Long, or null if no event index is found
    • withEventIndex

      default Entity<T> withEventIndex(Long index, String messageId)
      Updates the event index and message ID of the entity and returns the updated version of the entity.
      Parameters:
      index - the event index to set for the root entity
      messageId - the message ID associated with the event
      Returns:
      the updated entity corresponding to the current entity's ID and type, or null if no such entity can be found
    • withSequenceNumber

      default Entity<T> withSequenceNumber(long sequenceNumber)
      Returns an updated entity based on this with the specified sequence number.
      Parameters:
      sequenceNumber - the sequence number to assign to the entity
      Returns:
      the updated entity with the specified sequence number, or null if the entity could not be found in the entity hierarchy
    • timestamp

      default Instant timestamp()
      Retrieves the timestamp of the entity.
      Returns:
      the timestamp as an Instant obtained from the root entity
    • sequenceNumber

      default long sequenceNumber()
      Retrieves the sequence number of the current entity.
      Returns:
      the sequence number of the root entity
    • rootAnnotation

      default Aggregate rootAnnotation()
      Retrieves the root-level annotation of the aggregate, if any.
      Returns:
      the Aggregate annotation of the root entity, or null if not found
    • previous

      default Entity<T> previous()
      Retrieves the previous version of this entity.
      Returns:
      the previous state of the entity, or null if this is the first known version
    • playBackToEvent

      default Entity<T> playBackToEvent(Long eventIndex, String eventId)
      Finds a version of this entity matching the given eventIndex or eventId. This method plays back the aggregate until the aggregate's lastEventIndex() smaller or equal to eventIndex or lastEventId() equals eventId.
      Parameters:
      eventIndex - the index of the event to revert to, or null if the index is not provided
      eventId - the unique ID of the event to revert to
      Returns:
      the aggregate entity reverted to the specified event state
      Throws:
      IllegalStateException - if the playback to the event state fails
    • playBackToCondition

      default Optional<Entity<T>> playBackToCondition(Predicate<Entity<T>> condition)
      Plays back through older versions of this entity until a specified condition is met. This method starts from the current entity and iteratively moves to previous versions of the entity until the condition is satisfied or there are no older versions.
      Parameters:
      condition - the predicate condition to evaluate against each entity while playing back
      Returns:
      an Optional containing the first entity that meets the condition, or an empty Optional if no such entity is found
    • entities

      Collection<? extends Entity<?>> entities()
      Retrieves child entities of this entity.
      Returns:
      a collection containing child entities.
    • allEntities

      default Stream<Entity<?>> allEntities()
      Retrieves a stream of all entities, including the current entity and all nested entities.
      Returns:
      a Stream containing the current entity and all nested entities within it.
    • getEntity

      default <C> Optional<Entity<C>> getEntity(Object entityId)
      Retrieves an entity based on the provided entity ID. The entity can be matched either by its primary ID or by any of its aliases.
      Type Parameters:
      C - the type parameter representing the content or payload of the entity
      Parameters:
      entityId - the ID or alias of the entity to search for; if null, an empty Optional is returned
      Returns:
      an Optional containing the matching entity if found, or an empty Optional if no match exists
    • relationships

      default Set<Relationship> relationships()
      Retrieves the set of relationships between the aggregate root and all its entities.

      If the current entity is not a root entity, this method delegates to the root entity's relationships. If the root entity is empty, an empty set is returned. Otherwise, the relationships are computed based on the entity's ID, type, and aliases.

      Returns:
      a set of Relationship objects representing the relationships associated with the aggregate root.
    • associations

      default Set<Relationship> associations(Entity<?> previous)
      Determines the set of new associations (relationships) that are present in the current entity but not in the provided previous entity.
      Parameters:
      previous - The previous entity whose relationships will be excluded from the current entity's relationships.
      Returns:
      A set of relationships that exist in the current entity but not in the previous entity.
    • dissociations

      default Set<Relationship> dissociations(Entity<?> previous)
      Identifies and returns the set of relationships that are dissociated when compared to the relationships of the given previous entity.
      Parameters:
      previous - the entity whose relationships are to be compared against the current entity's relationships.
      Returns:
      a set of relationships that exist in the given entity but are not present in the current entity.
    • update

      Entity<T> update(UnaryOperator<T> function)
      Updates the current entity's value using the specified unary operator and returns a new entity containing the updated value.
      Parameters:
      function - the unary operator to apply to the current entity's value
      Returns:
      a new entity containing the updated value after applying the function
    • apply

      default Entity<T> apply(Object... events)
      Applies the given events to reconstruct or update the entity's state.
      Parameters:
      events - an array of events to be applied, represented as objects
      Returns:
      the resulting entity after applying the events
    • apply

      default Entity<T> apply(Collection<?> events)
      Applies a collection of events to the current entity, returning an updated entity.
      Parameters:
      events - a collection of events to be applied to the entity
      Returns:
      the updated entity after all events have been applied
    • apply

      default Entity<T> apply(Object event)
      Processes the given event and applies the corresponding logic based on its type.
      Parameters:
      event - the event object to be processed. It can be the payload of the event or an event message.
      Returns:
      the result of the operation as an Entity<T> instance.
    • apply

      default Entity<T> apply(Object event, Metadata metadata)
      Applies an event and associated metadata to produce a resulting entity.
      Parameters:
      event - the event object that will be applied
      metadata - metadata associated with the event
      Returns:
      the resulting entity after applying the event and metadata
    • apply

      default Entity<T> apply(DeserializingMessage eventMessage)
      Applies the given deserializing message to the entity.
      Parameters:
      eventMessage - the deserializing message to process and convert into an entity
      Returns:
      the entity resulting from applying the given deserializing message
    • apply

      Entity<T> apply(Message eventMessage)
      Applies the given message to the entity.
      Parameters:
      eventMessage - the message representing the event to be applied
      Returns:
      the updated or newly created Entity of type T
    • commit

      Entity<T> commit()
      Commits the current state of the entity, persisting any changes made to it. This method ensures that the modifications are saved. Typically, it is unnecessary to invoke this manually as it is automatically invoked after the current handler or consumer batch has completed.
      Returns:
      The updated entity after the commit operation is successfully completed.
    • assertLegal

      <E extends Exception> Entity<T> assertLegal(Object update) throws E
      Verifies that the provided update is legal given the current state of the aggregate. If so, the entity is returned; otherwise, it throws an appropriate exception.
      Type Parameters:
      E - the type of exception expected if the update is not legal
      Parameters:
      update - the update to be validated for compliance with the required rules
      Returns:
      the entity if the update is legal
      Throws:
      E - if the update fails to meet legal requirements
    • assertAndApply

      default Entity<T> assertAndApply(Object payloadOrMessage)
      Verifies that the provided update is legal given the current state of the aggregate and on success applies it to the aggregate. If not, it throws an appropriate exception.
      Parameters:
      payloadOrMessage - the input object to be applied; can be a payload or a message
      Returns:
      the resulting entity after application
    • assertAndApply

      default Entity<T> assertAndApply(Object payload, Metadata metadata)
      Verifies that the provided update is legal given the current state of the aggregate and on success applies it to the aggregate. If the update is not legal, it throws an appropriate exception.
      Parameters:
      payload - The object representing the payload to be validated and processed.
      metadata - The metadata associated with the payload for validation and processing.
      Returns:
      An Entity instance containing the result after processing the payload and metadata.
    • assertAndApply

      default Entity<T> assertAndApply(Object... updates)
      Applies a number of updates to the current entity after performing necessary legality assertions. If any of the updates is not legal, it rolls back the entity and throws an appropriate exception.
      Parameters:
      updates - an array of updates to be processed and applied to the entity
      Returns:
      an updated Entity instance after applying the provided updates
    • assertAndApply

      default Entity<T> assertAndApply(Collection<?> updates)
      Applies a collection of updates sequentially to the current entity after asserting each is legal, and returns the resulting entity. If any of the updates is not legal, it rolls back the entity and throws an appropriate exception.
      Parameters:
      updates - the collection of updates to be applied to the entity
      Returns:
      the resulting entity after applying the updates
    • possibleTargets

      default Iterable<Entity<?>> possibleTargets(Object update)
      Determines the possible target entities for the given update. The update can be a payload or an instance of HasMessage.

      The method evaluates the update against child entities of this entity and identifies which entities are valid targets.

      Parameters:
      update - the object to evaluate against the entities. If null, an empty list is returned.
      Returns:
      an iterable collection of entities that are considered valid targets for the provided update.
    • depth

      default int depth()
      Calculates the depth level of the current entity in the aggregate. The depth is determined by counting the number of parent entities above the current entity. The root entity has a depth of 0.
      Returns:
      the depth level of the current entity, where 0 indicates the root entity.