spring-data-jpa
Skill293 starsChanged 4 months agoMITView on GitHub
Use when generating or refactoring Spring Boot 4 JPA entities, repositories, queries, projections, persistence tests, entity relationships, embeddables, IDs, or Hibernate mappings. Covers Jakarta Persistence 3.2 imports, Hibernate 7 entity modeling, new-state detection, N+1 prevention, projections, keyset pagination, batch writes, and common agent mistakes.
2 other projects use a version of this.
Adopted by
Most recently taken up by
- Amplicode/spring-skillstheir own version, first seen Sep 2, 2026
- james-paul25/claude-skilltheir own version, first seen Jul 11, 2026
Other versions2 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 2
- Amplicode/spring-skills★ 126same name
- james-paul25/claude-skill★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository65 other files it gives its agents.
- ai-observabilitySkill
- api-versioningSkill
- configuration-propertiesSkill
- container-native-deploymentSkill
- domain-driven-designSkill
- event-driven-messagingSkill
- flyway-migrationsSkill
- hateoasSkill
- hexagonal-architectureSkill
- http-interface-clientsSkill
- idempotency-patternsSkill
- layered-architectureSkill
- mcp-serverSkill
- multi-module-mavenSkill
- multi-tenancySkill
- null-safetySkill
- oauth2-resource-serverSkill
- openapi-firstSkill
- problem-details-rfc9457Skill
- production-observabilitySkill
- resilience-retrySkill
- rest-api-conventionsSkill
- spring-ai-integrationSkill
- spring-batchSkill
- spring-boot-migrationSkill
- spring-cloud-gatewaySkill
- spring-data-jpaSkill
- spring-data-redisSkill
- spring-modulithSkill
- spring-security-jwtSkill
- testing-pyramidSkill
- transactional-patternsSkill
- webflux-reactive-patternsSkill
- ai-observabilitySkill
- api-versioningSkill
- configuration-propertiesSkill
- container-native-deploymentSkill
- domain-driven-designSkill
- event-driven-messagingSkill
- flyway-migrationsSkill
- hateoasSkill
- hexagonal-architectureSkill
- http-interface-clientsSkill
- idempotency-patternsSkill
- layered-architectureSkill
- mcp-serverSkill
- multi-module-mavenSkill
- multi-tenancySkill
- null-safetySkill
- oauth2-resource-serverSkill
- openapi-firstSkill
- problem-details-rfc9457Skill
- production-observabilitySkill
- resilience-retrySkill
- rest-api-conventionsSkill
- spring-ai-integrationSkill
- spring-batchSkill
- spring-boot-migrationSkill
- spring-cloud-gatewaySkill
- spring-data-redisSkill
- The first 60 shown.
The file
Show its rules and text
We split this skill into the rules it gives an agent
23 rules. About 0 are common, 9 are distinctive, and 14 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈9
Distinctive · estimate
This author's own choices. Worth a look.
14
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 18
Use an @Entity only for persistent state with identity and lifecycle.
- Very specific: line 86
Use jakarta.persistence.*, never javax.persistence.*.
- Distinctive: line 87
Keep entities non-final with a protected no-arg constructor so Hibernate can instantiate/proxy them.
- Distinctive: line 88
Do not use Java records for ordinary entities.
- Very specific: line 89
Use targeted Lombok (@Getter, protected @NoArgsConstructor), not @Data or broad @Setter.
- Distinctive: line 90
Prefer behavior methods and static factories over public setters/constructors.
- Very specific: line 92
Use @Enumerated(EnumType.STRING) with explicit column length.
- Very specific: line 93
Add @Version Long version for user-editable aggregates.
- Very specific: line 94
Prefer UUID or pooled sequence IDs.
- Distinctive: line 137
Never expose entities from controllers.
- Very specific: line 191
Put fetch = FetchType.LAZY on @ManyToOne and @OneToOne.
- Distinctive: line 192
Avoid unbounded bidirectional graphs.
- Very specific: line 193
Use orphanRemoval = true only when the parent truly owns the child's lifecycle.
- Very specific: line 194
Avoid @ManyToMany for business relationships with attributes.
- Distinctive: line 195
Do not serialize lazy relationships to JSON.
- Very specific: line 199
Do not generate entity equality with Lombok @Data.
- Distinctive: line 204
If the entity has a stable natural key, base equality on that key and enforce a unique database constraint.
- Distinctive: line 206
If it only has a generated ID, keep default object identity unless the project already has a proxy-safe generated-ID pattern.
- Very specific: line 208
Never include collections, mutable fields, or associations in equals, hashCode, or toString.
- Very specific: line 209
Use instanceof, not getClass(), when equality must work with Hibernate proxies.
- Distinctive: line 279
Use fetch joins and entity graphs only for bounded relationships.
- Very specific: line 284
Use Pageable for normal list screens:
- Very specific: line 290
Use keyset pagination for deep or infinite-scroll lists.
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Spring Data JPA (Boot 4 / Hibernate 7)
Spring Boot 4 manages Jakarta Persistence 3.2, Jakarta Validation 3.1, and Hibernate ORM 7.x. Use
Boot dependency management and import jakarta.persistence.* / jakarta.validation.*. Do not add
explicit Hibernate, JPA, or Validator versions unless the project has a deliberate override policy.
Entity Model Rules
Use an @Entity only for persistent state with identity and lifecycle. Use records for DTOs,
commands, and read models. Use @Embeddable for values stored inside an entity table.
@Entity
@Table(name = "orders", indexes = {
@Index(name = "idx_orders_customer_id", columnList = "customer_id"),
@Index(name = "idx_orders_status_created", columnList = "status, created_at")
})
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
@Column(nullable = false, updatable = false)
private UUID id;
@Version
private Long version;
@Column(name = "customer_id", nullable = false, updatable = false)
private UUID customerId;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 32)
private OrderStatus status;
@Embedded
private Money total;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
private List<OrderItem> items = new ArrayList<>();
@CreationTimestamp
@Column(name = "created_at", nullable = false, updatable = false)
private Instant createdAt;
@UpdateTimestamp
@Column(name = "updated_at", nullable = false)
private Instant updatedAt;
public static Order create(UUID customerId) {
Order order = new Order();
order.customerId = Objects.requireNonNull(customerId);
order.status = OrderStatus.DRAFT;
order.total = Money.zero("EUR");
return order;
}
public void addItem(UUID productId, int quantity, Money unitPrice) {
if (status != OrderStatus.DRAFT) {
throw new IllegalStateException("Cannot edit submitted order");
}
items.add(OrderItem.create(this, productId, quantity, unitPrice));
recalculateTotal();
}
private void recalculateTotal() {
total = items.stream()
.map(OrderItem::subtotal)
.reduce(Money.zero("EUR"), Money::add);
}
}Rules:
- Use
jakarta.persistence.*, neverjavax.persistence.*. - Keep entities non-final with a protected no-arg constructor so Hibernate can instantiate/proxy them.
- Do not use Java records for ordinary entities. Records are good DTOs and sometimes embeddables.
- Use targeted Lombok (
@Getter, protected@NoArgsConstructor), not@Dataor broad@Setter. - Prefer behavior methods and static factories over public setters/constructors.
- Initialize collections inline. JPA collection fields should not be null.
- Use
@Enumerated(EnumType.STRING)with explicit column length. Never useORDINAL. - Add
@Version Long versionfor user-editable aggregates. Use wrapperLong, not primitivelong. - Prefer
UUIDor pooled sequence IDs. AvoidGenerationType.IDENTITYon high-write tables because it disables insert batching. - Validate request DTOs at the boundary; enforce entity invariants inside behavior methods.
Embeddables and DTOs
@Embeddable
public record Money(
@Column(name = "amount", nullable = false, precision = 19, scale = 2)
BigDecimal amount,
@Column(name = "currency", nullable = false, length = 3)
String currency
) {
public Money {
Objects.requireNonNull(amount);
Objects.requireNonNull(currency);
if (amount.signum() < 0) {
throw new IllegalArgumentException("Amount cannot be negative");
}
}
public static Money zero(String currency) {
return new Money(BigDecimal.ZERO, currency);
}
public Money add(Money other) {
if (!currency.equals(other.currency)) {
throw new IllegalArgumentException("Currency mismatch");
}
return new Money(amount.add(other.amount), currency);
}
public Money multiply(int quantity) {
if (quantity < 1) {
throw new IllegalArgumentException("Quantity must be positive");
}
return new Money(amount.multiply(BigDecimal.valueOf(quantity)), currency);
}
}Never expose entities from controllers. Map entities to response records:
public record OrderResponse(UUID id, String status, BigDecimal total, Instant createdAt) {
static OrderResponse from(Order order) {
return new OrderResponse(
order.getId(),
order.getStatus().name(),
order.getTotal().amount(),
order.getCreatedAt());
}
}Relationships
Map the database shape first. Prefer normal foreign keys: @ManyToOne on the owning side and
@OneToMany(mappedBy = ...) only when parent-to-child navigation is actually needed.
@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
class OrderItem {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "order_id", nullable = false, foreignKey = @ForeignKey(name = "fk_order_item_order"))
private Order order;
@Column(name = "product_id", nullable = false, updatable = false)
private UUID productId;
private int quantity;
private Money unitPrice;
static OrderItem create(Order order, UUID productId, int quantity, Money unitPrice) {
OrderItem item = new OrderItem();
item.order = Objects.requireNonNull(order);
item.productId = Objects.requireNonNull(productId);
item.quantity = quantity;
item.unitPrice = Objects.requireNonNull(unitPrice);
return item;
}
Money subtotal() {
return unitPrice.multiply(quantity);
}
}- Put
fetch = FetchType.LAZYon@ManyToOneand@OneToOne; to-one mappings are eager by default. - Avoid unbounded bidirectional graphs. Add back-references only when required.
- Use
orphanRemoval = trueonly when the parent truly owns the child's lifecycle. - Avoid
@ManyToManyfor business relationships with attributes; model the join row as an entity. - Do not serialize lazy relationships to JSON. Map to DTOs inside a transaction.
equals and hashCode
Do not generate entity equality with Lombok @Data. It includes mutable fields and associations,
which can trigger lazy loading, recursion, and hash changes.
Preferred options:
- If the entity has a stable natural key, base equality on that key and enforce a unique database constraint.
- If it only has a generated ID, keep default object identity unless the project already has a proxy-safe generated-ID pattern.
- Never include collections, mutable fields, or associations in
equals,hashCode, ortoString. - Use
instanceof, notgetClass(), when equality must work with Hibernate proxies.
@Override
public boolean equals(Object other) {
return other instanceof Customer that
&& email != null
&& email.equals(that.getEmail());
}
@Override
public int hashCode() {
return email == null ? 0 : email.hashCode();
}Repositories and Query Patterns
public interface OrderRepository extends JpaRepository<Order, UUID> {
boolean existsByCustomerIdAndStatus(UUID customerId, OrderStatus status);
Optional<Order> findByIdAndCustomerId(UUID id, UUID customerId);
@EntityGraph(attributePaths = {"items"})
Optional<Order> findById(UUID id);
@Query("""
select o
from Order o
where o.status = :status
order by o.createdAt desc, o.id desc
""")
List<Order> findRecentByStatus(OrderStatus status, Limit limit);
}Use:
- Derived queries for simple filters.
@Queryfor explicit joins, keyset pagination, and complex predicates.@EntityGraphfor bounded graph loading.- Projections for read-only API views.
exists...queries instead offind...().isPresent()checks.
Avoid:
findAll()in endpoints.- Native SQL unless JPQL cannot express the query or the database-specific feature is intentional.
- Returning entities for read-only list views when a projection is enough.
N+1 Prevention
Identify N+1 by looking for lazy association access inside loops or JSON serialization of entities.
@EntityGraph(attributePaths = {"items", "items.product"})
Optional<Order> findWithItemsAndProductsById(UUID id);
public interface OrderSummary {
UUID getId();
UUID getCustomerId();
OrderStatus getStatus();
Instant getCreatedAt();
}
List<OrderSummary> findByStatus(OrderStatus status);Use fetch joins and entity graphs only for bounded relationships. For list endpoints, prefer projections to avoid loading entire aggregate graphs.
Pagination
Use Pageable for normal list screens:
Page<Order> findByStatus(OrderStatus status, Pageable pageable);Use keyset pagination for deep or infinite-scroll lists. OFFSET pagination scans and discards
skipped rows.
@Query("""
select o
from Order o
where o.status = :status
and (o.createdAt < :lastCreatedAt
or (o.createdAt = :lastCreatedAt and o.id < :lastId))
order by o.createdAt desc, o.id desc
""")
List<Order> findNextPage(OrderStatus status, Instant lastCreatedAt, UUID lastId, Limit limit);The (createdAt, id) tuple keeps the cursor stable when timestamps collide. Back it with an index
like (status, created_at desc, id desc).
Batch Writes
Enable JDBC batching for write-heavy workloads:
spring:
jpa:
properties:
hibernate:
jdbc.batch_size: 50
order_inserts: true
order_updates: trueGenerationType.IDENTITY disables insert batching because Hibernate needs the generated key after
each row. Use UUIDs or pooled sequences when batch insert throughput matters.
New-State Detection
Spring Data JPA detects new entities by nullable wrapper @Version first, then nullable ID. A
primitive version cannot be used because JPA treats 0 as the first persisted version.
For manually assigned IDs, add @Version Long version or implement Persistable with an isNew
flag cleared by @PostPersist and @PostLoad. Use the template in
templates/BaseAssignedIdEntity.java.
Gotchas
- Agent imports
javax.persistence.*- Boot 4 usesjakarta.persistence.*. - Agent creates entity records - use records for DTOs/embeddables, not ordinary entities.
- Agent puts
@Dataon entities - generates setters and unsafe equality; use targeted@Getter. - Agent makes entities
finalor constructors private - breaks Hibernate proxy/instantiation. - Agent uses
FetchType.EAGER- useLAZYon to-one and many-to-many relationships. - Agent uses
@Enumerated(EnumType.ORDINAL)- useSTRING. - Agent uses primitive
long version- use nullable wrapperLong. - Agent omits
@Versionon editable aggregates - lost updates are not detected. - Agent returns entities from controllers - map to DTO records.
- Agent calls
findAll()for list endpoints - requirePageable,Limit, or a projection query. - Agent uses
OFFSETpagination on huge tables - switch to keyset for deep pages. - Agent includes lazy associations in equality or
toString- causes lazy loads and recursion. - Agent maps every relationship bidirectionally - add back-references only when required.
- Agent uses
@ManyToManyfor business links with attributes - model the join row as an entity. - Agent batches inserts with
GenerationType.IDENTITY- batching is silently off; use UUID/sequence.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

