Skip to main content
AIDevOps
  • Learn
  • Learning Paths
  • Practice
  • Open Source
  • Books
  • Engineering

    AI DevOpsThe full map of building and operating AI servicesLLMOpsLLM deployment Β· evaluation Β· observabilityHands-on ProjectsBuild AI Agent projects

    Knowledge

    DocsTechnical documentationBlogEngineering articlesPloggerDevelopment log feed

    Validate

    Certification3-level skills certification Β· coming soon
AI Models
LlamaTutorial|MistralTutorial|GemmaTutorial|DeepSeekTutorial|QwenTutorial
🌱 Spring Cloud
Spring Intro & RoadmapSpring Cloud GatewaySpring BootJava|Spring AISpring SecuritySpring BatchSpring JPA
πŸ€– AI Applied Development
Applied AI Intro & RoadmapHugging FaceLangChainLlamaIndexLLMOps|LangGraphMCPMulti-AgentAgent Evaluation
🧠 AI Core
AI Intro & RoadmapML FundamentalsLLM Fundamentals|Python AIC++|PyTorchTensorFlowJAX
🧠 AI Agent Development
Finance AI AgentLLM API ServerStock Investing AgentAIOps AI AgentEducation AI AgentCoding AI Agent
🐳 DevOps
DevOps Intro & RoadmapLinuxDockerCI/CD|Kubernetes BasicsK8s AdvancedPrometheusGrafana
🧱 Infrastructure
Infrastructure Intro & RoadmapNginxRedis
☁️ Cloud
Cloud Intro & RoadmapAWSGCPAzureNCPCloudflare
🎨 Frontend
Frontend Intro & RoadmapJavaScriptTypeScript|ReactNext.js|VueNuxt|Electron
πŸ“± Mobile
Mobile Intro & RoadmapKotlinAndroidFlutter
βš™οΈ Backend
Backend Intro & RoadmapPython BasicsFastAPIDjangoFlask|CGoGinNode.js
πŸ’Ύ Database
DB Intro & RoadmapCore SQLOracleMySQLPostgreSQL|MongoDBVector DB
πŸ§ͺ Testing
k6JMeternGrinder
AIDevOps

Engineering AI. From Code to Production.
An engineering learning platform for building and operating AI and AI Agents

Learn

  • All Guides
  • Learning Paths
  • AI Tutorial
  • Practice
  • Books

Resources

  • AI DevOps
  • LLMOps
  • Hands-on Projects
  • Docs
  • Blog
  • Plogger
  • Open Source
  • Certification (coming soon)

Start Here

  • AI Core Roadmap
  • AI Applied Development Roadmap
  • Spring Cloud Roadmap
  • DevOps Roadmap
  • Infrastructure Roadmap

Β 

  • Cloud Roadmap
  • Frontend Roadmap
  • Mobile Roadmap
  • Backend Roadmap
  • Database Roadmap
Β© 2026 AIDevOps. All rights reserved.
Terms of ServicePrivacy PolicySitemaptestforge.kr
  1. Home
  2. Learn
  3. Spring Cloud
  4. Spring JPA
Guide to data access with Spring Boot

πŸ—„οΈ Spring JPA Complete Guide

Visitors

Build a practical data access layer with Spring Data JPA and QueryDSL on Spring Boot: Entity design, association mapping, JPQL/QueryDSL, solving N+1, transactions, paging, and performance optimization.

  • Intermediate
  • Updated Oct 1, 2026
  • ~6 min read
  • 10 sections
  • 10 code examples

Learning Paths that include this guide

This guide is one step in the paths below. Study it together with the steps before and after.

  • Spring Cloud Engineer β†’
Entity & ORM designDynamic queries with QueryDSLFixing N+1 performanceSpring Boot data layer

Related frameworks & environments

πŸƒSpring Bootβ†’β˜•Javaβ†’πŸ”Spring Securityβ†’βš™οΈSpring Batchβ†’

Contents

0 / 13
  1. How to use this guide
  2. Architecture diagrams
  3. What is Spring Data JPA?
  4. Spring Boot project setup
  5. Entity design
  6. Association mapping
  7. Repository & query methods
  8. JPQL & @Query
  9. Dynamic queries with QueryDSL
  10. Solving the N+1 problem
  11. Transactions & the persistence context
  12. Paging & sorting
  13. Frequently asked questions
Contents 13 sections
  1. How to use this guide
  2. Architecture diagrams
  3. What is Spring Data JPA?
  4. Spring Boot project setup
  5. Entity design
  6. Association mapping
  7. Repository & query methods
  8. JPQL & @Query
  9. Dynamic queries with QueryDSL
  10. Solving the N+1 problem
  11. Transactions & the persistence context
  12. Paging & sorting
  13. Frequently asked questions

How to use this guide

How to read it

Understanding Spring JPA as a real-world workflow

Build a practical data access layer with Spring Data JPA and QueryDSL on Spring Boot: Entity design, association mapping, JPQL/QueryDSL, solving N+1, transactions, paging, and performance optimization. Rather than listing concepts, this guide is organized so you can follow the content in the order you have to make decisions on a real project.

Key perspective

Backend / systems development

Before syntax, pin down the boundaries a request crosses: validation, processing, storage, and response.

Entity & ORM designDynamic queries with QueryDSLFixing N+1 performanceSpring Boot data layer

Architecture diagrams

To make what you read stick, it helps to capture the flow as a picture first. The two diagrams below are reference maps you can keep coming back to while learning Spring JPA.

Learning flow

Rendering diagram…

Architecture view

Rendering diagram…

What is Spring Data JPA?

When you first open Spring JPA, the big picture matters more than individual commands. This section starts with the problems the concepts ahead were created to solve.

Spring Data JPA provides the Repository abstraction on top of JPA. It generates queries from method names alone and lets you express complex queries with @Query and QueryDSL, cutting repetitive DAO code considerably.
LayerTechnologyRole
ORMJPA / HibernateObject-relational mapping, running JPQL queries
RepositorySpring Data JPAAutomatic query generation from method names
Dynamic queriesQueryDSLType-safe composition of conditions
Schema managementFlyway / LiquibaseVersioned DB migrations

Spring Boot project setup

Here you look at Spring Boot project setup alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

Adding QueryDSL as well lets type-safe queries be verified at compile time instead of string-based JPQL. Even if you use ddl-auto: update for convenience in local development, always change it to validate or none in production, to prevent the incident of the application accidentally altering the production DB schema.
build.gradle.ktsKOTLIN
plugins {
    id("java")
    id("org.springframework.boot") version "3.3.5"
    id("io.spring.dependency-management") version "1.1.6"
}

java { toolchain { languageVersion.set(JavaLanguageVersion.of(21)) } }

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    implementation("org.springframework.boot:spring-boot-starter-validation")
    implementation("com.querydsl:querydsl-jpa:5.1.0:jakarta")
    annotationProcessor("com.querydsl:querydsl-apt:5.1.0:jakarta")
    annotationProcessor("jakarta.annotation:jakarta.annotation-api")
    annotationProcessor("jakarta.persistence:jakarta.persistence-api")
    compileOnly("org.projectlombok:lombok")
    annotationProcessor("org.projectlombok:lombok")
    runtimeOnly("org.postgresql:postgresql")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
}
application.ymlYAML
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/mydb
    username: ${DB_USER}
    password: ${DB_PASS}
  jpa:
    hibernate:
      ddl-auto: validate
    show-sql: false
    properties:
      hibernate:
        format_sql: true
        default_batch_fetch_size: 100  # prevents N+1

Entity design

Here you look at Entity design alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

Set immutable fields only through the constructor and keep Setters to a minimum. Auditing manages createdAt and updatedAt automatically. Providing business methods that reveal intent, like activate()/deactivate(), instead of a general-purpose Setter such as setStatus() makes it clear from the Entity code alone which state changes are allowed, and invalid state transitions can be blocked inside the method.
User.javaJAVA
@Entity @Table(name = "users")
@Getter @Builder @NoArgsConstructor @AllArgsConstructor
@EntityListeners(AuditingEntityListener.class)
public class User {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

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

    @Column(nullable = false, unique = true)
    private String email;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    private UserStatus status;

    @CreatedDate
    @Column(updatable = false)
    private LocalDateTime createdAt;

    @LastModifiedDate
    private LocalDateTime updatedAt;

    // Business methods (instead of Setters)
    public void activate()    { this.status = UserStatus.ACTIVE; }
    public void deactivate()  { this.status = UserStatus.INACTIVE; }
}

Association mapping

Here you look at Association mapping alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

Default to unidirectional associations and switch to bidirectional only when needed. Avoid @ManyToMany and define the join table Entity yourself. @ManyToMany makes it hard to add columns to the join table or optimize queries, so in practice, where the relationship itself often needs attributes such as assignedAt, creating the join Entity from the start and expressing it as two @ManyToOne associations is far more flexible.
JAVA
// ── One-to-Many (post : comments) ───────────────
@Entity
public class Post {
    @Id @GeneratedValue(strategy = IDENTITY) private Long id;
    private String title;

    @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Comment> comments = new ArrayList<>();

    public void addComment(Comment comment) {
        comments.add(comment);
        comment.setPost(this);
    }
}

@Entity
public class Comment {
    @Id @GeneratedValue(strategy = IDENTITY) private Long id;
    private String content;

    @ManyToOne(fetch = FetchType.LAZY)  // always LAZY
    @JoinColumn(name = "post_id")
    private Post post;
}

// ── Many-to-Many β†’ join table Entity ─────────────
@Entity
public class UserRole {
    @Id @GeneratedValue(strategy = IDENTITY) private Long id;

    @ManyToOne(fetch = LAZY) @JoinColumn(name = "user_id") private User user;
    @ManyToOne(fetch = LAZY) @JoinColumn(name = "role_id") private Role role;

    private LocalDateTime assignedAt;
}

Repository & query methods

Here you look at Repository & query methods alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

Extending JpaRepository provides CRUD and paging out of the box. Simple queries are generated automatically from the method naming rules. Once conditions get complex the method names grow too long, so from that point write the JPQL yourself with @Query, and for bulk operations that change many rows at once, @Modifying is required so the change goes directly to the database, independently of the persistence context.
UserRepository.javaJAVA
public interface UserRepository extends JpaRepository<User, Long> {

    // Queries generated automatically from method names
    Optional<User> findByEmail(String email);
    boolean existsByEmail(String email);
    List<User> findByStatusOrderByCreatedAtDesc(UserStatus status);
    long countByStatus(UserStatus status);

    // @Query β€” JPQL
    @Query("SELECT u FROM User u WHERE u.createdAt >= :from AND u.status = :status")
    List<User> findActiveAfter(@Param("from") LocalDateTime from,
                               @Param("status") UserStatus status);

    // Bulk update β€” @Modifying required
    @Modifying
    @Query("UPDATE User u SET u.status = :status WHERE u.id IN :ids")
    int bulkUpdateStatus(@Param("ids") List<Long> ids,
                         @Param("status") UserStatus status);
}

JPQL & @Query

Here you look at JPQL & @Query alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

JPQL is written in terms of Entity names and field names. With nativeQuery = true, native SQL can be run as well.
JAVA
// ── Fetch Join (solves N+1) ───────────────────────
@Query("SELECT p FROM Post p JOIN FETCH p.comments WHERE p.id = :id")
Optional<Post> findWithComments(@Param("id") Long id);

// ── DTO Projection ────────────────────────────────
@Query("SELECT new com.example.dto.UserSummary(u.id, u.name, u.email) " +
       "FROM User u WHERE u.status = 'ACTIVE'")
List<UserSummary> findActiveSummaries();

// ── Native Query ──────────────────────────────────
@Query(value = "SELECT * FROM users WHERE email ILIKE %:keyword%",
       nativeQuery = true)
List<User> searchByEmailNative(@Param("keyword") String keyword);

Dynamic queries with QueryDSL

Here you look at Dynamic queries with QueryDSL alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

QueryDSL composes conditions in a type-safe way. Build null-safe dynamic conditions with BooleanBuilder or BooleanExpression.
UserQueryRepository.javaJAVA
@Repository
@RequiredArgsConstructor
public class UserQueryRepository {

    private final JPAQueryFactory queryFactory;
    private final QUser user = QUser.user;

    public List<User> search(UserSearchCondition cond) {
        return queryFactory
            .selectFrom(user)
            .where(
                emailContains(cond.getEmail()),
                statusEq(cond.getStatus()),
                createdAfter(cond.getFrom())
            )
            .orderBy(user.createdAt.desc())
            .offset(cond.getOffset())
            .limit(cond.getSize())
            .fetch();
    }

    // excluded from the conditions when null (null-safe dynamic conditions)
    private BooleanExpression emailContains(String email) {
        return StringUtils.hasText(email) ? user.email.containsIgnoreCase(email) : null;
    }
    private BooleanExpression statusEq(UserStatus status) {
        return status != null ? user.status.eq(status) : null;
    }
    private BooleanExpression createdAfter(LocalDateTime from) {
        return from != null ? user.createdAt.goe(from) : null;
    }
}

Solving the N+1 problem

Here you look at Solving the N+1 problem alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

N+1 is the problem of running N extra queries, one per row, for an associated Entity. Solve it with a Fetch Join, an EntityGraph, or batch_fetch_size.
Rendering diagram…
JAVA
// ── The problem ───────────────────────────────────
// N+1 occurs: after loading posts, an extra comments SELECT runs for each post
List<Post> posts = postRepository.findAll();
posts.forEach(p -> p.getComments().size()); // N extra queries

// ── Fix 1: Fetch Join ─────────────────────────────
@Query("SELECT DISTINCT p FROM Post p JOIN FETCH p.comments")
List<Post> findAllWithComments();

// ── Fix 2: @EntityGraph ───────────────────────────
@EntityGraph(attributePaths = {"comments"})
List<Post> findAll();

// ── Fix 3: global setting in application.yml ─────
// hibernate.default_batch_fetch_size: 100
// β†’ loads 100 at a time with an IN query (effective for collection N+1)

Transactions & the persistence context

Here you look at Transactions & the persistence context alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

Declare @Transactional on the Service layer. Apply readOnly=true to read-only transactions to optimize performance. An Entity loaded inside a transaction keeps being tracked by the persistence context (the first-level cache), so just changing a field value gets the change written as an UPDATE automatically at commit time, with no separate save() call (dirty checking).
Rendering diagram…
UserService.javaJAVA
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)  // read-only by default
public class UserService {

    private final UserRepository userRepository;

    // Read β€” stays readOnly
    public UserResponse findById(Long id) {
        return userRepository.findById(id)
            .map(UserResponse::from)
            .orElseThrow(() -> new EntityNotFoundException("User: " + id));
    }

    // Write β€” overrides readOnly
    @Transactional
    public UserResponse create(CreateUserRequest req) {
        if (userRepository.existsByEmail(req.getEmail())) {
            throw new DuplicateEmailException(req.getEmail());
        }
        User user = userRepository.save(
            User.builder()
                .name(req.getName())
                .email(req.getEmail())
                .status(UserStatus.ACTIVE)
                .build()
        );
        return UserResponse.from(user);
    }

    // Dirty checking β€” no save() needed
    @Transactional
    public void activate(Long id) {
        User user = userRepository.findById(id).orElseThrow();
        user.activate(); // UPDATE issued automatically at transaction commit
    }
}

Paging & sorting

Here you look at Paging & sorting alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

Taking a Pageable as a parameter generates the offset/limit query automatically. When using it with QueryDSL, split out the count query to optimize performance.
UserController.javaJAVA
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @GetMapping
    public Page<UserResponse> list(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(defaultValue = "createdAt,desc") String[] sort) {

        Pageable pageable = PageRequest.of(page, size,
            Sort.by(Arrays.stream(sort)
                .map(s -> s.split(","))
                .map(a -> a[1].equalsIgnoreCase("desc")
                    ? Sort.Order.desc(a[0])
                    : Sort.Order.asc(a[0]))
                .collect(Collectors.toList())));

        return userService.findAll(pageable);
    }
}

// QueryDSL paging (count query split out)
public Page<UserSummary> searchPaged(UserSearchCondition cond, Pageable pageable) {
    List<UserSummary> content = queryFactory
        .select(Projections.constructor(UserSummary.class, user.id, user.name, user.email))
        .from(user)
        .where(statusEq(cond.getStatus()))
        .orderBy(user.createdAt.desc())
        .offset(pageable.getOffset())
        .limit(pageable.getPageSize())
        .fetch();

    JPAQuery<Long> countQuery = queryFactory
        .select(user.count())
        .from(user)
        .where(statusEq(cond.getStatus()));

    return PageableExecutionUtils.getPage(content, pageable, countQuery::fetchOne);
}

Spring JPA: frequently asked questions

How are JPA, Hibernate, and Spring Data JPA related?

JPA is the standard specification for mapping objects to tables, and Hibernate is a library that implements it. Spring Data JPA is a convenience layer on top: you declare a repository interface and it generates the basic query and save code.

What is the N+1 problem and how do I fix it?

After one query loads a list, an extra query runs per item to load its related entity. Load the related data in one go with a fetch join or an EntityGraph, or set a batch size so it is loaded with IN queries. The best prevention is a habit of reading the SQL that actually runs in the logs.

Should associations be eager or lazy?

Default to lazy loading and bring related data in with a fetch join in the query only where it is needed together. Eager loading always loads the related data even when it is not needed and causes queries you did not expect.

← Previous guideSpring Batch