Optimizing article and comment queries with Spring Data JPA
Separate read and write services, batch author and collection lookups, and test a ten-day editing limit using an injected Clock in Kotlin.
Article and comment endpoints exposed two separate problems. The list response fetched collections and authors one query at a time, and updates mixed remote uploads with database work. I split query and command services around the same database and gave both paths explicit transaction boundaries.
The examples use Kotlin 1.9.25, Spring Boot 3.5, Java 21, and Spring Data JPA with Hibernate 6.
Separating query and command services
ArticleQueryService and CommentQueryService assemble response models. ArticleCommandService and CommentCommandService handle state changes. Sharing a single database kept the consistency model simple. A separate projection store would also require synchronization, recovery, and decisions about stale reads.
flowchart TD
C["ArticleController / CommentController"]
Q["QueryService (readOnly)"]
M["Command service"]
S["External storage"]
D["Repository & PostgreSQL"]
C -->|"GET"| Q
C -->|"POST / PATCH / DELETE"| M
M -->|"Upload image"| S
Q -->|"Batch fetch"| D
M -->|"TransactionTemplate"| D
| Aspect | Query service | Command service |
|---|---|---|
| Transaction | @Transactional(readOnly = true) at class level | Writable @Transactional or TransactionTemplate |
| Hibernate behavior | Read-only flush policy and reduced dirty checking | Dirty checking of managed entities |
| Collaborators | Repositories and StringRedisTemplate | Repositories, StorageService, and Clock |
When a command uploads images, I complete the external call before opening the database transaction. TransactionTemplate covers persistence and leaves the upload outside the connection’s checkout window. The ImgBB integration shows that boundary in more detail.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// src/main/kotlin/org/project/portfolio/article/application/ArticleCommandService.kt
@Service
class ArticleCommandService(
private val articleRepository: ArticleRepository,
private val userRepository: UserRepository,
private val storageService: StorageService,
private val eventPublisher: ApplicationEventPublisher,
private val transactionTemplate: TransactionTemplate,
private val clock: Clock,
) {
fun createArticle(
email: String,
articleForm: ArticleForm,
): ArticleResponse {
val uploadedImages = articleForm.images.map { storageService.uploadFile(it) }
return checkNotNull(
transactionTemplate.execute {
val user: User = userRepository.findByEmail(email)
?: throw NotFoundException(User::class.java, mapOf("email" to email))
val article: Article = articleRepository.save(
Article.create(
title = articleForm.title,
content = articleForm.content,
authorId = user.id,
images = uploadedImages,
tags = articleForm.tags,
),
)
ArticleResponse.from(
article = article,
author = UserSummaryResponse.from(user),
)
},
)
}
}
Mapping ordered images and distinct tags
Images use List<String> with @OrderColumn(name = "image_order"). The position belongs to the persistent data because the response displays images in order. Tags use MutableSet<String>, where the model requires uniqueness and has no ordering rule.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// src/main/kotlin/org/project/portfolio/article/domain/Article.kt
@Entity
@SoftDelete(columnName = "is_deleted")
class Article(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long = 0L,
@Column(length = 400)
var title: String,
@Column(columnDefinition = "TEXT")
var content: String,
@ElementCollection
@CollectionTable(name = "article_images")
@OrderColumn(name = "image_order")
var images: List<String> = mutableListOf(),
@ElementCollection
@CollectionTable(name = "article_tags")
var tags: MutableSet<String> = mutableSetOf(),
var authorId: Long,
var viewCount: Long = 0,
) : BaseTimeEntity() {
fun update(
title: String?,
content: String?,
images: List<String>? = null,
tags: List<String>? = null,
) {
title?.let { this.title = it }
content?.let { this.content = it }
images?.let { this.images = it }
tags?.let {
this.tags.clear()
this.tags.addAll(it.map { tag -> tag.trim() }.filter { tag -> tag.isNotEmpty() })
}
}
}
An unordered collection mapped as a Hibernate bag may be deleted and reinserted when the ORM cannot target individual rows. A set gives Hibernate element identities to compare with its snapshot. Mutating the managed set through clear() and addAll() preserves Hibernate’s collection wrapper so it can compute changes from the before and after contents. SQL behavior still depends on the mapping, so inspect it when the collection size matters.
I kept title and body filtering in one repository query and normalized blank search input in the service with keyword?.trim()?.takeIf { it.isNotEmpty() }.
1
2
3
4
5
6
7
8
9
10
11
12
13
// src/main/kotlin/org/project/portfolio/article/domain/ArticleRepository.kt
@Query(
"""
SELECT a FROM Article a
WHERE :keyword IS NULL OR :keyword = ''
OR a.title LIKE CONCAT('%', :keyword, '%')
OR a.content LIKE CONCAT('%', :keyword, '%')
""",
)
fun searchByKeyword(
@Param("keyword") keyword: String? = null,
pageable: Pageable,
): Page<Article>
A leading wildcard in %keyword% rules out an ordinary B-tree prefix range scan. If substring search grows expensive, examine the actual query plan before choosing a PostgreSQL pg_trgm index or a full-text engine. The appropriate index depends on whether the product needs literal substrings or ranked terms.
Batching collections and author lookups
I store authorId: Long on articles and comments instead of creating an ORM association to the user aggregate. A view still needs each author’s details and every article’s tags and images. Those are two distinct N+1 paths.
- Hibernate groups lazy collection loads with
default_batch_fetch_size: 100. The exact number of collection queries depends on which owners are already present in the persistence context. - The query service deduplicates author IDs and loads them with
findAllById. It indexes the result by ID and performs the join in memory while building the response.
1
2
3
4
5
6
7
# src/main/resources/application.yml
spring:
jpa:
open-in-view: false
properties:
hibernate:
default_batch_fetch_size: 100
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// src/main/kotlin/org/project/portfolio/article/application/ArticleQueryService.kt
@Service
@Transactional(readOnly = true)
class ArticleQueryService(
private val articleRepository: ArticleRepository,
private val stringRedisTemplate: StringRedisTemplate,
private val commentRepository: CommentRepository,
private val userRepository: UserRepository,
) {
fun getArticles(
keyword: String?,
pageable: Pageable,
): Page<ArticleSummaryResponse> {
val articles = articleRepository.searchByKeyword(
keyword = keyword?.trim()?.takeIf { it.isNotEmpty() },
pageable = pageable,
)
val authorIds = articles.content.map { it.authorId }.distinct()
val authorsById = userRepository.findAllById(authorIds).associateBy { it.id }
return articles.map { article ->
ArticleSummaryResponse.from(
article = article,
author = UserSummaryResponse.from(authorsById[article.authorId]),
)
}
}
fun getArticle(id: Long): ArticleResponse {
val article = articleRepository.findByIdOrNull(id)
?: throw NotFoundException(Article::class.java, mapOf("articleId" to id))
val comments = commentRepository.findByArticleId(id)
val userIds = (comments.map { it.authorId } + article.authorId).distinct()
val usersById = userRepository.findAllById(userIds).associateBy { it.id }
return ArticleResponse.from(
article = article,
author = UserSummaryResponse.from(usersById[article.authorId]),
comments = comments.map { comment ->
CommentResponse.from(
comment = comment,
author = UserSummaryResponse.from(usersById[comment.authorId]),
)
},
)
}
}
The detail query combines the article author and each comment author into one ID set. With open-in-view: false, the query service also maps the lazy collections into the DTO before it returns. This keeps serialization independent of the persistence context.
Serving comments as a page
Loading every comment with the article detail becomes expensive as discussion grows. I moved the paged responses to GET /api/v1/articles/{articleId}/comments. The details endpoint can now stay bounded even when a post has many comments.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/main/kotlin/org/project/portfolio/article/presentation/CommentController.kt
@GetMapping
@Operation(summary = "List article comments by page")
fun getComments(
@PathVariable articleId: Long,
@PageableDefault(page = 0, size = 20, sort = ["createdAt"], direction = Sort.Direction.ASC)
@ParameterObject pageable: Pageable,
): ResponseEntity<PagedModel<CommentResponse>> {
return ResponseEntity.ok(
PagedModel(
commentQueryService.getComments(
articleId = articleId,
pageable = pageable,
),
),
)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// src/main/kotlin/org/project/portfolio/article/application/CommentQueryService.kt
@Service
@Transactional(readOnly = true)
class CommentQueryService(
private val articleRepository: ArticleRepository,
private val commentRepository: CommentRepository,
private val userRepository: UserRepository,
) {
fun getComments(
articleId: Long,
pageable: Pageable,
): Page<CommentResponse> {
if (!articleRepository.existsById(articleId)) {
throw NotFoundException(Article::class.java, mapOf("articleId" to articleId))
}
val comments = commentRepository.findByArticleId(articleId, pageable)
val authorIds = comments.content.map { it.authorId }.distinct()
val authorsById = userRepository.findAllById(authorIds).associateBy { it.id }
return comments.map { comment ->
CommentResponse.from(
comment = comment,
author = UserSummaryResponse.from(authorsById[comment.authorId]),
)
}
}
}
CommentQueryService calls existsById first so a missing article gets a 404 instead of an empty page. It fetches the comments for the requested page and loads the page’s authors in one batch. The controller wraps the result in PagedModel to avoid exposing the internal JSON shape of PageImpl as a response contract.
Testing the ten-day editing rule
I put the comparison in Article.isEditableAt(now) and injected a Clock. Production uses Clock.systemUTC(). A unit test can pick an exact instant with Clock.fixed(...), regardless of when the test runs.
1
2
3
4
5
6
// src/main/kotlin/org/project/portfolio/config/ClockConfig.kt
@Configuration
class ClockConfig {
@Bean
fun clock(): Clock = Clock.systemUTC()
}
1
2
3
4
5
6
7
8
// src/main/kotlin/org/project/portfolio/article/domain/Article.kt (excerpt)
companion object {
const val EDITABLE_DAYS: Long = 10L
}
fun isEditableAt(now: Instant): Boolean {
return createdAt.until(now, ChronoUnit.DAYS) < EDITABLE_DAYS
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// src/main/kotlin/org/project/portfolio/article/domain/validator/ArticleValidator.kt
@Component
class ArticleValidator(
private val articleRepository: ArticleRepository,
private val userRepository: UserRepository,
private val clock: Clock = Clock.systemUTC(),
) {
fun isEditable(
articleId: Long,
email: String,
): Boolean {
val article = articleRepository.findByIdOrNull(articleId)
?: throw NotFoundException(Article::class.java, mapOf("articleId" to articleId))
val user: User = userRepository.findByEmail(email)
?: throw NotFoundException(User::class.java, mapOf("email" to email))
if (article.authorId != user.id) {
return false
}
return article.isEditableAt(Instant.now(clock))
}
}
The update endpoint calls @articleValidator.isEditable(#articleId, authentication.name) from its @PreAuthorize rule. The rule also allows administrators. An unauthorized or expired edit returns 403 before the command spends time uploading images. If the decision must stay valid throughout a lengthy write, recheck the invariant in the command’s transaction.
Store creation times as unambiguous instants and keep database/session time-zone settings consistent with UTC. Test one instant just before the editing deadline, the deadline itself, and an instant just after it.
- Inspect SQL for a page with multiple authors and collections to verify that additional lookups are batched.
- Compare the SQL for adding one tag with the SQL for editing image order.
- Call the paged comments endpoint for both a missing article and an existing article with no comments.
- Deny an expired edit before making a storage request and test the administrator exception separately.
