Entities, repositories, and queries—persist data with Spring Data JPA and Hibernate.
Spring Data JPA makes database access declarative. Here’s how to model entities and write queries.
JPA and Spring Data
Basics
Entity — A class mapped to a table with @Entity. Use @Id and @GeneratedValue for the primary key. Map relationships with @OneToMany, @ManyToOne, etc. Avoid bidirectional cascades on large collections.
Repository — Extend JpaRepository<Entity, Id>. You get CRUD and paging. Add method names (e.g. findByEmail) or @Query for custom JPQL or SQL.
Transactions — @Transactional on service methods. Read-only for queries when possible. Lazy loading works inside a transaction; watch out for N+1 (use fetch join or DTOs).
Hibernate — The default JPA provider. Use Hibernate-specific features (e.g. filters, envers) only when needed; stick to JPA for portability.
Spring Data usage (Java backends):
Data access in Spring projects
N+1 and performance
Use @EntityGraph or JOIN FETCH for associations you always need. Prefer DTO projections (constructor expression or interface) over loading full entities when you only need a few fields. Enable SQL logging in dev to spot N+1.
Spring Data JPA tutorial:
Takeaway
Spring Data JPA reduces boilerplate and keeps queries in one place. Model entities clearly; use repositories and transactions. Tame N+1 with fetch strategies and projections.