Jpa Patterns logo

Jpa Patterns

CommunityPopular
affaan-m
jpa-patterns

Patrones JPA/Hibernate para diseño de entidades, relaciones, optimización de consultas, transacciones, auditoría, indexación, paginación y pooling en Spring Boot.

Overview

Publisheraffaan-m
RepositoryECC
Skill namejpa-patterns
Stars
261.1K
Forks
39.1K
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by affaan-m on GitHub. Read the source before you install it.

Installation

Install the Jpa Patterns AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/affaan-m/ECC.git /tmp/ECC
mkdir -p .claude/skills
cp -r /tmp/ECC/docs/es/skills/jpa-patterns .claude/skills/jpa-patterns
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Jpa Patterns in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Jpa Patterns on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Jpa Patterns is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Patrones JPA/Hibernate

Usar para modelado de datos, repositorios y ajuste de rendimiento en Spring Boot.

Cuándo Activar

  • Diseñar entidades JPA y mapeos de tablas
  • Definir relaciones (@OneToMany, @ManyToOne, @ManyToMany)
  • Optimizar consultas (prevención de N+1, estrategias de fetch, proyecciones)
  • Configurar transacciones, auditoría o soft deletes
  • Configurar paginación, ordenamiento o métodos de repositorio personalizados
  • Ajustar el connection pool (HikariCP) o caché de segundo nivel

Diseño de Entidades

java
@Entity
@Table(name = "markets", indexes = {
  @Index(name = "idx_markets_slug", columnList = "slug", unique = true)
})
@EntityListeners(AuditingEntityListener.class)
public class MarketEntity {
  @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(nullable = false, length = 200)
  private String name;

  @Column(nullable = false, unique = true, length = 120)
  private String slug;

  @Enumerated(EnumType.STRING)
  private MarketStatus status = MarketStatus.ACTIVE;

  @CreatedDate private Instant createdAt;
  @LastModifiedDate private Instant updatedAt;
}

Habilitar auditoría:

java
@Configuration
@EnableJpaAuditing
class JpaConfig {}

Relaciones y Prevención de N+1

java
@OneToMany(mappedBy = "market", cascade = CascadeType.ALL, orphanRemoval = true)
private List<PositionEntity> positions = new ArrayList<>();
  • Usar lazy loading por defecto; usar JOIN FETCH en consultas cuando sea necesario
  • Evitar EAGER en colecciones; usar proyecciones DTO para rutas de lectura
java
@Query("select m from MarketEntity m left join fetch m.positions where m.id = :id")
Optional<MarketEntity> findWithPositions(@Param("id") Long id);

Patrones de Repositorio

java
public interface MarketRepository extends JpaRepository<MarketEntity, Long> {
  Optional<MarketEntity> findBySlug(String slug);

  @Query("select m from MarketEntity m where m.status = :status")
  Page<MarketEntity> findByStatus(@Param("status") MarketStatus status, Pageable pageable);
}
  • Usar proyecciones para consultas ligeras:
java
public interface MarketSummary {
  Long getId();
  String getName();
  MarketStatus getStatus();
}
Page<MarketSummary> findAllBy(Pageable pageable);

Transacciones

  • Anotar métodos de servicio con @Transactional
  • Usar @Transactional(readOnly = true) para rutas de lectura y optimizar
  • Elegir la propagación cuidadosamente; evitar transacciones de larga duración
java
@Transactional
public Market updateStatus(Long id, MarketStatus status) {
  MarketEntity entity = repo.findById(id)
      .orElseThrow(() -> new EntityNotFoundException("Market"));
  entity.setStatus(status);
  return Market.from(entity);
}

Paginación

java
PageRequest page = PageRequest.of(pageNumber, pageSize, Sort.by("createdAt").descending());
Page<MarketEntity> markets = repo.findByStatus(MarketStatus.ACTIVE, page);

Para paginación tipo cursor, incluir id > :lastId en JPQL con ordenamiento.

Indexación y Rendimiento

  • Agregar índices para filtros comunes (status, slug, claves foráneas)
  • Usar índices compuestos que coincidan con patrones de consulta (status, created_at)
  • Evitar select *; proyectar solo las columnas necesarias
  • Escrituras en lote con saveAll y hibernate.jdbc.batch_size

Connection Pooling (HikariCP)

Propiedades recomendadas:

spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.validation-timeout=5000

Para el manejo de LOB en PostgreSQL, agregar:

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

Caché

  • La caché de primer nivel es por EntityManager; evitar mantener entidades entre transacciones
  • Para entidades con muchas lecturas, considerar la caché de segundo nivel con cautela; validar la estrategia de evicción

Migraciones

  • Usar Flyway o Liquibase; nunca depender de auto DDL de Hibernate en producción
  • Mantener las migraciones idempotentes y aditivas; evitar eliminar columnas sin un plan

Pruebas de Acceso a Datos

  • Preferir @DataJpaTest con Testcontainers para replicar producción
  • Verificar la eficiencia SQL con logs: establecer logging.level.org.hibernate.SQL=DEBUG y logging.level.org.hibernate.orm.jdbc.bind=TRACE para valores de parámetros

Recuerda: Mantener las entidades ligeras, las consultas intencionales y las transacciones cortas. Prevenir N+1 con estrategias de fetch y proyecciones, e indexar para tus rutas de lectura/escritura.

Frequently asked questions

What does the Jpa Patterns AI skill do?

Patrones JPA/Hibernate para diseño de entidades, relaciones, optimización de consultas, transacciones, auditoría, indexación, paginación y pooling en Spring Boot.

Why use Jpa Patterns on TypingMind?

Because you install it once and use it with any model. Jpa Patterns is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Jpa Patterns in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/affaan-m/ECC/tree/main/docs/es/skills/jpa-patterns. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Jpa Patterns?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Jpa Patterns?

As many as you like. As long as a model supports skills, you can use Jpa Patterns with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Jpa Patterns AI skill free?

Yes. It is published on GitHub by affaan-m under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇