Contents 13 sections
- How to use this guide
- Architecture diagrams
- What is Spring Data JPA?
- Spring Boot project setup
- Entity design
- Association mapping
- Repository & query methods
- JPQL & @Query
- Dynamic queries with QueryDSL
- Solving the N+1 problem
- Transactions & the persistence context
- Paging & sorting
- Frequently asked questions
How to use this guide
How to read itUnderstanding 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 perspectiveBackend / 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
Architecture view
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.
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.
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")
}
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.
@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.
// ββ 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.
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.
// ββ 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.
@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.
// ββ 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).
@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.
@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.