Skip to content
jpa-entity-creator logo

JPA Entity Creator

jpa-entity-creator

Creates JPA entities following best practices.

SKILL.md

Full skill instructions

JPA Entity Creator

Instructions

The following are key principles to follow while creating JPA entities:

  • Make sure to create the recommended package structure for Spring Boot projects
  • Use application generated TSID or UUID as a String for primary keys
  • Create a Value Object to represent the primary key and use @EmbeddedId annotation
  • Create a protected no-arg constructor for JPA
  • Create a public constructor with all required fields
  • Validate state and throw exceptions for invalid inputs
  • Explicitly define table names for all entities
  • Explicitly define column names for all fields
  • Use enum types for enum fields and @Enumerated(EnumType.STRING) annotation
  • For logically related fields, create a Value Object to represent them
  • When using value objects, embed them with @Embedded and @AttributeOverrides
  • Add domain methods that operate on entity state
  • Use optimistic locking with @Version
  • Create BaseEntity for audit fields(createdAt, updatedAt) and extend all entities from it

IdentityGenerator

To use TSID, add the following dependency:

<dependency>
    <groupId>io.hypersistence</​groupId>
    <artifactId>hypersistence-utils-hibernate-71</​artifactId>
    <version>3.14.1</​version>
</​dependency>

Now you can use TSID to generate IDs as follows:

import io.hypersistence.tsid.TSID;

public class IdGenerator {
    private IdGenerator() {}

    public static String generateString() {
        return TSID.Factory.getTsid().toString();
    }

    public static Long generateLong() {
        return TSID.Factory.getTsid().toLong();
    }
}

Value Object for Primary Key

public record EventId(String id) {
    public EventId {
        if (id == null || id.trim().isBlank()) {
            throw new IllegalArgumentException("Event id cannot be null or empty");
        }
    }

    public static EventId of(String id) {
        return new EventId(id);
    }

    public static EventId generate() {
        return new EventId(IdGenerator.generateString());
    }
}

BaseEntity with Auditing Support

File: BaseEntity.java

import jakarta.persistence.Column;
import jakarta.persistence.MappedSuperclass;

import java.time.Instant;

@MappedSuperclass
public abstract class BaseEntity {

    @Column(name = "created_at", nullable = false, updatable = false)
    protected Instant createdAt;

    @Column(name = "updated_at", nullable = false)
    protected Instant updatedAt;

    public Instant getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Instant createdAt) {
        this.createdAt = createdAt;
    }

    public Instant getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Instant updatedAt) {
        this.updatedAt = updatedAt;
    }
}

AssertUtil class to validate input parameters

Create a AssertUtil class with static methods to validate input parameters.

public class AssertUtil {
    private AssertUtil() {}

    public static <T> T requireNotNull(T obj, String message) {
        if (obj == null)
            throw new IllegalArgumentException(message);
        return obj;
    }
}

Example JPA Entity Class

While Creating a new JPA entity class, extend it from BaseEntity:

import jakarta.persistence.*;

import java.time.Instant;

@Entity
@Table(name = "events")
class EventEntity extends BaseEntity {

    @EmbeddedId
    @AttributeOverride(name = "id", column = @Column(name = "id", nullable = false))
    private EventId id;

    @Embedded
    @AttributeOverrides({
        @AttributeOverride(name = "title", column = @Column(name = "title", nullable = false)),
        @AttributeOverride(name = "description", column = @Column(name = "description")),
        @AttributeOverride(name = "imageUrl", column = @Column(name = "image_url"))
    })
    private EventDetails details;

    @Enumerated(EnumType.STRING)
    @Column(name = "event_type", nullable = false)
    private EventType type;

    //.. other fields

    @Version
    private int version;

    // Protected constructor for JPA
    protected EventEntity() {}

    // Constructor with all required fields
    public EventEntity(EventId id,
                       EventCode code,
                       EventDetails details,
                       Schedule schedule,
                       EventType type,
                       //...
                       EventLocation location) {
        this.id = AssertUtil.requireNotNull(id, "Event id cannot be null");
        this.code = AssertUtil.requireNotNull(code, "Event code cannot be null");
        this.details = AssertUtil.requireNotNull(details, "Event details cannot be null");
        this.schedule = AssertUtil.requireNotNull(schedule, "Event schedule cannot be null");
        this.type = AssertUtil.requireNotNull(type, "Event type cannot be null");
        this.location = AssertUtil.requireNotNull(location, "Event location cannot be null");
        //...
    }

    // Factory method for creating new entities
    public static EventEntity createDraft(
            EventDetails details,
            Schedule schedule,
            EventType type,
            TicketPrice ticketPrice,
            Capacity capacity,
            EventLocation location) {

        return new EventEntity(
                EventId.generate(),
                EventCode.generate(),
                details,
                schedule,
                type,
                EventStatus.DRAFT,
                ticketPrice,
                capacity,
                location);
    }

    // Domain logic methods
    public boolean hasFreeSeats() {
        return capacity == null || capacity.value() == null || capacity.value() > registrationsCount;
    }

    public boolean isPublished() {
        return status == EventStatus.PUBLISHED;
    }

    // Getters
}

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View