Skip to content

Marthym/entity

Repository files navigation

Entity GitHub license

Quality Gate Status Coverage Maintainability Rating

Size Limit CLI

Entity is a small library that handles the notion of model entity. Entity offers an elegant way of working with business objects that may or may not have an identifier.

The entity can hold, or not, some metadata. For example ID of the user who creates the entity, the date of creation, the last update, ... This metadata was embedded through an EnumMap, the most efficient structure to store unknown number of key/value pairs.

The jackson package offers a module for serializing and deserializing these entities in a flat manner.

Installation

Use the package manager maven to install entity.

<dependency>
    <groupId>fr.ght1pc9kc</groupId>
    <artifactId>entity-api</artifactId>
    <version>VERSION</version>
</dependency>
<dependency>
    <groupId>fr.ght1pc9kc</groupId>
    <artifactId>entity-jackson</artifactId>
    <version>VERSION</version>
</dependency>

for gradle

compile "fr.ght1pc9kc:entity-api:VERSION"
compile "fr.ght1pc9kc:entity-jackson:VERSION"

Usage

Create an entity

import fr.ght1pc9kc.entity.api.Entity;
import java.time.Instant;

import static fr.ght1pc9kc.demo.DefaultMeta.createdBy;
import static fr.ght1pc9kc.demo.DefaultMeta.createdAt;

Entity<String> basic = Entity.identify("May the force")
        .withId("4TH");

Entity<String> simple = Entity.identify("May the force")
        .meta(createdBy, "Yoda")
        .meta(createdAt, Instant.now())
        .withId("4TH");

Entity<String> verySimple = Entity.identify("May the force").withId("4TH");

Entity<Saber> POLYMORPHIC_ENTITY = Entity
        .<Saber>identify(new LightSaber(Color.GREEN, 1))
        .meta(createdAt, Instant.parse("2024-01-20T15:06:42.546Z"))
        .meta(createdBy, "okenobi")
        .withId("LIGHTSABER");

Include Jackson module

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import fr.ght1pc9kc.entity.jackson.EntityModule;

ObjectMapper mapper = new ObjectMapper()
        .registerModule(new JavaTimeModule())
        .registerModule(new EntityModule())
        .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

Using JavaTimeModule is mandatory to allow serialize Instant, WRITE_DATES_AS_TIMESTAMPS is optional but provide more beautiful json.

{
  "_id": "LIGHTSABER",
  "_createdAt": "2024-01-20T15:06:42.546Z",
  "_createdBy": "okenobi",
  "@type": "LIGHT",
  "blade": 1,
  "color": "GREEN"
}

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT