Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ with https://plugins.gradle.org/plugin/org.springframework.boot/3.4.3[Spring Boo
|link:data-mongodb-audit[Spring Data MongoDB Audit] |Enable Audit with Spring Data MongoDB
|link:data-mongodb-full-text-search[Spring Data MongoDB: Full Text Search] |Implement link:https://docs.mongodb.com/manual/text-search/[MongoDB Full Text Search] with Spring Data MongoDB
|link:data-mongodb-transactional[Spring Data MongoDB: Transactional] |Enable `@Transactional` support for Spring Data MongoDB
|link:data-repository-definition[Spring Data: Repository Definition] |Implement custom repository interfaces with `@RepositoryDefinition` annotation
|link:data-rest-validation[Spring Data REST: Validation] |Perform validation with Spring Data REST
|link:graphql[Spring GraphQL Server] |Implement GraphQL server with Spring GraphQL Server
|link:jooq[jOOQ] | Implement an alternative to Jpa using https://www.jooq.org/[jOOQ] and Gradle
Expand Down
3 changes: 3 additions & 0 deletions data-repository-definition/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/gradlew text eol=lf
*.bat text eol=crlf
*.jar binary
37 changes: 37 additions & 0 deletions data-repository-definition/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/

### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/

### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/

### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/

### VS Code ###
.vscode/
101 changes: 101 additions & 0 deletions data-repository-definition/README.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
= Spring Data: Repository Definition
:source-highlighter: highlight.js
Rashidi Zin <rashidi@zin.my>
1.0, March 22, 2025
:toc:
:nofooter:
:icons: font
:url-quickref: https://github.com/rashidi/spring-boot-tutorials/tree/master/data-repository-definition

Implement custom repository interfaces with @RepositoryDefinition annotation.

include::../docs/badges.adoc[]

== Background

link:https://spring.io/projects/spring-data[Spring Data] provides a consistent programming model for data access while still retaining the special traits of the underlying data store. It makes it easy to use data access technologies, relational and non-relational databases, map-reduce frameworks, and cloud-based data services.

When working with Spring Data, we typically create repository interfaces by extending one of the provided base interfaces such as `CrudRepository`, `JpaRepository`, or `MongoRepository`. However, sometimes we may want to define a repository with only specific methods, without inheriting all the methods from these base interfaces.

This is where the `@RepositoryDefinition` annotation comes in. It allows us to define a repository interface with only the methods we need, providing more control over the repository's API.

== Domain Class

We have a simple domain class, link:{url-quickref}/src/main/java/zin/rashidi/data/repositorydefinition/note/Note.java[Note], which is a Java record with three fields: `id`, `title`, and `content`.

[source,java]
----
record Note(@Id Long id, String title, String content) {
}
----

The `@Id` annotation from Spring Data marks the `id` field as the primary key.

== Repository Definition

Instead of extending a base repository interface, we use the `@RepositoryDefinition` annotation to define our repository interface, link:{url-quickref}/src/main/java/zin/rashidi/data/repositorydefinition/note/NoteRepository.java[NoteRepository].

[source,java]
----
@RepositoryDefinition(domainClass = Note.class, idClass = Long.class)
interface NoteRepository {

List<Note> findByTitleContainingIgnoreCase(String title);

}
----

The `@RepositoryDefinition` annotation takes two parameters:
- `domainClass`: The entity class that this repository manages (in this case, `Note.class`)
- `idClass`: The type of the entity's ID field (in this case, `Long.class`)

With this annotation, Spring Data will create a repository implementation for us, just like it would for a repository that extends a base interface. The difference is that our repository only has the methods we explicitly define, in this case, just `findByTitleContainingIgnoreCase`.

== Benefits of @RepositoryDefinition

Using `@RepositoryDefinition` offers several benefits:

1. **Minimalist API**: You only expose the methods you need, making the API cleaner and more focused.
2. **Explicit Contract**: The repository interface clearly shows what operations are supported.
3. **Reduced Surface Area**: By not inheriting methods from base interfaces, you reduce the risk of unintended operations being performed.
4. **Flexibility**: You can define repositories for any domain class without being tied to a specific persistence technology's base interface.

== Testing

We can link:{url-quickref}/src/test/java/zin/rashidi/data/repositorydefinition/note/NoteRepositoryTests.java[test our repository] using Spring Boot's testing support with Testcontainers for PostgreSQL.

[source,java]
----
@Import(TestcontainersConfiguration.class)
@DataJdbcTest
@SqlMergeMode(MERGE)
@Sql(statements = "CREATE TABLE note (id BIGINT PRIMARY KEY, title VARCHAR(50), content TEXT);", executionPhase = BEFORE_TEST_CLASS)
class NoteRepositoryTests {

@Autowired
private NoteRepository notes;

@Test
@Sql(statements = {
"INSERT INTO note (id, title, content) VALUES ('1', 'Right Turn', 'Step forward. Step forward and turn right. Collect.')",
"INSERT INTO note (id, title, content) VALUES ('2', 'Left Turn', 'Step forward. Reverse and turn left. Collect.')",
"INSERT INTO note (id, title, content) VALUES ('3', 'Double Spin', 'Syncopated. Double spin. Collect.')"
})
@DisplayName("Given there are two entries with the word 'turn' in the title When I search by 'turn' in title Then Right Turn And Left Turn should be returned")
void findByTitleContainingIgnoreCase() {
var turns = notes.findByTitleContainingIgnoreCase("turn");

assertThat(turns)
.extracting("title")
.containsOnly("Right Turn", "Left Turn");
}
}
----

The test verifies that our repository method `findByTitleContainingIgnoreCase` correctly finds notes with titles containing the word "turn", ignoring case.

== Conclusion

The `@RepositoryDefinition` annotation provides a way to create custom repository interfaces with only the methods you need, without inheriting all the methods from base interfaces. This gives you more control over your repository's API and makes your code more explicit about what operations are supported.

While extending base interfaces like `CrudRepository` or `JpaRepository` is convenient for most cases, using `@RepositoryDefinition` can be a good choice when you want to limit the operations that can be performed on your entities or when you want to create a more focused and explicit API.
32 changes: 32 additions & 0 deletions data-repository-definition/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.4.4'
id 'io.spring.dependency-management' version '1.1.7'
}

group = 'zin.rashidi'
version = '0.0.1-SNAPSHOT'

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

repositories {
mavenCentral()
}

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
runtimeOnly 'org.postgresql:postgresql'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.boot:spring-boot-testcontainers'
testImplementation 'org.testcontainers:junit-jupiter'
testImplementation 'org.testcontainers:postgresql'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

tasks.named('test') {
useJUnitPlatform()
}
1 change: 1 addition & 0 deletions data-repository-definition/settings.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
rootProject.name = 'data-repository-definition'
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package zin.rashidi.data.repositorydefinition;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DataRepositoryDefinitionApplication {

public static void main(String[] args) {
SpringApplication.run(DataRepositoryDefinitionApplication.class, args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package zin.rashidi.data.repositorydefinition.note;

import org.springframework.data.annotation.Id;

/**
* @author Rashidi Zin
*/
record Note(@Id Long id, String title, String content) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package zin.rashidi.data.repositorydefinition.note;

import org.springframework.data.repository.RepositoryDefinition;

import java.util.List;

/**
* @author Rashidi Zin
*/
@RepositoryDefinition(domainClass = Note.class, idClass = Long.class)
interface NoteRepository {

List<Note> findByTitleContainingIgnoreCase(String title);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
spring.application.name=data-repository-definition
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package zin.rashidi.data.repositorydefinition;

import org.springframework.boot.SpringApplication;

public class TestDataRepositoryDefinitionApplication {

public static void main(String[] args) {
SpringApplication.from(DataRepositoryDefinitionApplication::main).with(TestcontainersConfiguration.class).run(args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package zin.rashidi.data.repositorydefinition;

import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.context.annotation.Bean;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.utility.DockerImageName;

@TestConfiguration(proxyBeanMethods = false)
public class TestcontainersConfiguration {

@Bean
@ServiceConnection
PostgreSQLContainer<?> postgresContainer() {
return new PostgreSQLContainer<>(DockerImageName.parse("postgres:latest"));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package zin.rashidi.data.repositorydefinition.note;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlMergeMode;
import zin.rashidi.data.repositorydefinition.TestcontainersConfiguration;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.BEFORE_TEST_CLASS;
import static org.springframework.test.context.jdbc.SqlMergeMode.MergeMode.MERGE;

/**
* @author Rashidi Zin
*/
@Import(TestcontainersConfiguration.class)
@DataJdbcTest
@SqlMergeMode(MERGE)
@Sql(statements = "CREATE TABLE note (id BIGINT PRIMARY KEY, title VARCHAR(50), content TEXT);", executionPhase = BEFORE_TEST_CLASS)
class NoteRepositoryTests {

@Autowired
private NoteRepository notes;

@Test
@Sql(statements = {
"INSERT INTO note (id, title, content) VALUES ('1', 'Right Turn', 'Step forward. Step forward and turn right. Collect.')",
"INSERT INTO note (id, title, content) VALUES ('2', 'Left Turn', 'Step forward. Reverse and turn left. Collect.')",
"INSERT INTO note (id, title, content) VALUES ('3', 'Double Spin', 'Syncopated. Double spin. Collect.')"
})
@DisplayName("Given there are two entries with the word 'turn' in the title When I search by 'turn' in title Then Right Turn And Left Turn should be returned")
void findByTitleContainingIgnoreCase() {
var turns = notes.findByTitleContainingIgnoreCase("turn");

assertThat(turns)
.extracting("title")
.containsOnly("Right Turn", "Left Turn");
}

}
1 change: 1 addition & 0 deletions settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ include('data-mongodb-audit')
include('data-mongodb-full-text-search')
include('data-mongodb-tc-data-load')
include('data-mongodb-transactional')
include('data-repository-definition')
include('data-rest-validation')
include('graphql')
include('jooq')
Expand Down
Loading