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
FieldsModifier and TypeFieldDescriptionstatic 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 TypeMethodDescriptionCollection
<?> aliases()
Retrieves a collection of aliases associated with this entity.Retrieves a stream of all entities, including the current entity and all nested entities.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.Applies the given message to the entity.apply
(DeserializingMessage eventMessage) Applies the given deserializing message to the entity.Processes the given event and applies the corresponding logic based on its type.Applies the given events to reconstruct or update the entity's state.Applies an event and associated metadata to produce a resulting entity.apply
(Collection<?> events) Applies a collection of events to the current entity, returning an updated entity.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.assertAndApply
(Object... updates) Applies a number of updates to the current entity after performing necessary legality assertions.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.assertAndApply
(Collection<?> updates) Applies a collection of updates sequentially to the current entity after asserting each is legal, and returns the resulting entity.assertLegal
(Object update) 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.commit()
Commits the current state of the entity, persisting any changes made to it.default int
depth()
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<?>> entities()
Retrieves child entities of this entity.get()
Retrieves the current instance of the entity.static String
getAggregateId
(HasMetadata message) Retrieves the aggregate ID from the metadata of the given message.static Class
<?> getAggregateType
(HasMetadata message) Retrieves the aggregate type from the metadata of the given message.Retrieves an entity based on the provided entity ID.static Long
getSequenceNumber
(HasMetadata message) Retrieves the sequence number from the metadata of the given message.static boolean
hasSequenceNumber
(HasMetadata message) 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.ifPresent
(UnaryOperator<Entity<T>> action) 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
isEmpty()
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
isRoot()
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> mapIfPresent
(Function<Entity<T>, U> action) Maps the entity to a new value if the entity is present.Entity
<?> parent()
Retrieves the parent entity of the current entity.playBackToCondition
(Predicate<Entity<T>> condition) Plays back through older versions of this entity until a specified condition is met.playBackToEvent
(Long eventIndex, String eventId) Finds a version of this entity matching the given eventIndex or eventId.possibleTargets
(Object update) Determines the possible target entities for the given update.previous()
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
<?> root()
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.type()
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.withEventIndex
(Long index, String messageId) Updates the event index and message ID of the entity and returns the updated version of the entity.withSequenceNumber
(long sequenceNumber) Returns an updated entity based on this with the specified sequence number.Sets the type of the entity to the specified class and returns the updated entity.
-
Field Details
-
loading
-
applying
-
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
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
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
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
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<?>
, ornull
if the metadata key is not present
-
hasSequenceNumber
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
Retrieves the sequence number from the metadata of the given message. The sequence number is extracted as aLong
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
, ornull
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
Retrieves the type of the entity.- Returns:
- the class type of the entity, or null if the type has not been defined
-
withType
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
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 aUnaryOperator
that accepts and returns anEntity<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
-
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
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
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
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
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
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
Retrieves the highest event index associated with the aggregate. The method resolves thelastEventIndex()
. 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
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 entitymessageId
- 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
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
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
Retrieves the root-level annotation of the aggregate, if any.- Returns:
- the
Aggregate
annotation of the root entity, or null if not found
-
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
Finds a version of this entity matching the given eventIndex or eventId. This method plays back the aggregate until the aggregate'slastEventIndex()
smaller or equal to eventIndex orlastEventId()
equals eventId.- Parameters:
eventIndex
- the index of the event to revert to, or null if the index is not providedeventId
- 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
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
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
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 emptyOptional
is returned- Returns:
- an
Optional
containing the matching entity if found, or an emptyOptional
if no match exists
-
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
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
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
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
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
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
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
Applies an event and associated metadata to produce a resulting entity.- Parameters:
event
- the event object that will be appliedmetadata
- metadata associated with the event- Returns:
- the resulting entity after applying the event and metadata
-
apply
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
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
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
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
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
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
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
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
Determines the possible target entities for the given update. The update can be a payload or an instance ofHasMessage
.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.
-