|
| 1 | += Spring Data: Repository Definition |
| 2 | +:source-highlighter: highlight.js |
| 3 | +Rashidi Zin <rashidi@zin.my> |
| 4 | +1.0, March 22, 2025 |
| 5 | +:toc: |
| 6 | +:nofooter: |
| 7 | +:icons: font |
| 8 | +:url-quickref: https://github.com/rashidi/spring-boot-tutorials/tree/master/data-repository-definition |
| 9 | + |
| 10 | +Implement custom repository interfaces with @RepositoryDefinition annotation. |
| 11 | + |
| 12 | +include::../docs/badges.adoc[] |
| 13 | + |
| 14 | +== Background |
| 15 | + |
| 16 | +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. |
| 17 | + |
| 18 | +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. |
| 19 | + |
| 20 | +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. |
| 21 | + |
| 22 | +== Domain Class |
| 23 | + |
| 24 | +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`. |
| 25 | + |
| 26 | +[source,java] |
| 27 | +---- |
| 28 | +record Note(@Id Long id, String title, String content) { |
| 29 | +} |
| 30 | +---- |
| 31 | + |
| 32 | +The `@Id` annotation from Spring Data marks the `id` field as the primary key. |
| 33 | + |
| 34 | +== Repository Definition |
| 35 | + |
| 36 | +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]. |
| 37 | + |
| 38 | +[source,java] |
| 39 | +---- |
| 40 | +@RepositoryDefinition(domainClass = Note.class, idClass = Long.class) |
| 41 | +interface NoteRepository { |
| 42 | +
|
| 43 | + List<Note> findByTitleContainingIgnoreCase(String title); |
| 44 | +
|
| 45 | +} |
| 46 | +---- |
| 47 | + |
| 48 | +The `@RepositoryDefinition` annotation takes two parameters: |
| 49 | +- `domainClass`: The entity class that this repository manages (in this case, `Note.class`) |
| 50 | +- `idClass`: The type of the entity's ID field (in this case, `Long.class`) |
| 51 | + |
| 52 | +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`. |
| 53 | + |
| 54 | +== Benefits of @RepositoryDefinition |
| 55 | + |
| 56 | +Using `@RepositoryDefinition` offers several benefits: |
| 57 | + |
| 58 | +1. **Minimalist API**: You only expose the methods you need, making the API cleaner and more focused. |
| 59 | +2. **Explicit Contract**: The repository interface clearly shows what operations are supported. |
| 60 | +3. **Reduced Surface Area**: By not inheriting methods from base interfaces, you reduce the risk of unintended operations being performed. |
| 61 | +4. **Flexibility**: You can define repositories for any domain class without being tied to a specific persistence technology's base interface. |
| 62 | + |
| 63 | +== Testing |
| 64 | + |
| 65 | +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. |
| 66 | + |
| 67 | +[source,java] |
| 68 | +---- |
| 69 | +@Import(TestcontainersConfiguration.class) |
| 70 | +@DataJdbcTest |
| 71 | +@SqlMergeMode(MERGE) |
| 72 | +@Sql(statements = "CREATE TABLE note (id BIGINT PRIMARY KEY, title VARCHAR(50), content TEXT);", executionPhase = BEFORE_TEST_CLASS) |
| 73 | +class NoteRepositoryTests { |
| 74 | +
|
| 75 | + @Autowired |
| 76 | + private NoteRepository notes; |
| 77 | +
|
| 78 | + @Test |
| 79 | + @Sql(statements = { |
| 80 | + "INSERT INTO note (id, title, content) VALUES ('1', 'Right Turn', 'Step forward. Step forward and turn right. Collect.')", |
| 81 | + "INSERT INTO note (id, title, content) VALUES ('2', 'Left Turn', 'Step forward. Reverse and turn left. Collect.')", |
| 82 | + "INSERT INTO note (id, title, content) VALUES ('3', 'Double Spin', 'Syncopated. Double spin. Collect.')" |
| 83 | + }) |
| 84 | + @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") |
| 85 | + void findByTitleContainingIgnoreCase() { |
| 86 | + var turns = notes.findByTitleContainingIgnoreCase("turn"); |
| 87 | +
|
| 88 | + assertThat(turns) |
| 89 | + .extracting("title") |
| 90 | + .containsOnly("Right Turn", "Left Turn"); |
| 91 | + } |
| 92 | +} |
| 93 | +---- |
| 94 | + |
| 95 | +The test verifies that our repository method `findByTitleContainingIgnoreCase` correctly finds notes with titles containing the word "turn", ignoring case. |
| 96 | + |
| 97 | +== Conclusion |
| 98 | + |
| 99 | +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. |
| 100 | + |
| 101 | +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. |
0 commit comments