### Running Couchbase Docker Container for Spring Data Example Source: https://github.com/spring-projects/spring-data-examples/blob/main/couchbase/transactions/README.md This command initiates a Couchbase Docker container, mapping necessary ports for cluster management, data access, and administrative interfaces. It's the first step to setting up the database for the Spring Data Couchbase example. ```Shell docker run -d --name db -p 8091-8097:8091-8097 -p 11210:11210 -p 11207:11207 -p 18091-18095:18091-18095 -p 18096:18096 -p 18097:18097 couchbase ``` -------------------------------- ### Setup MongoDB for Spring Data REST Application Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/starbucks/README.md Instructions to install and initialize MongoDB, creating a data directory and starting the database server, which is a prerequisite for running the Spring Data REST application. ```Shell mkdir data bin/mongod --dbpath=data ``` -------------------------------- ### Install GraalVM and Native Image Tooling Source: https://github.com/spring-projects/spring-data-examples/blob/main/jdbc/graalvm-native/README.adoc Instructions for installing GraalVM using SDKMAN! and subsequently installing the native-image component required for native compilation. ```Shell sdk install java .r17-grl gu install native-image ``` -------------------------------- ### Run Elasticsearch Locally Source: https://github.com/spring-projects/spring-data-examples/blob/main/elasticsearch/reactive/README.md Provides command-line instructions to navigate to the Elasticsearch directory and start the Elasticsearch server, which is a prerequisite for running the Spring Data Elasticsearch examples. ```bash $ cd elasticsearch $ ./bin/elasticsearch ``` -------------------------------- ### Run Local Redis Instance with Docker Source: https://github.com/spring-projects/spring-data-examples/blob/main/README.adoc This command starts a Redis 5.0 Docker container, mapping its default port (6379) to the host machine. This is required to run the Spring Data Redis examples and tests. ```Shell $ docker run -p 6379:6379 redis:5.0 ``` -------------------------------- ### Perform Query-by-Example with Spring Data R2DBC Source: https://github.com/spring-projects/spring-data-examples/blob/main/r2dbc/query-by-example/README.adoc Demonstrates how to create and use `Example` objects for querying. The first part shows a basic example, and the second part illustrates using `ExampleMatcher` for more complex matching criteria like `endsWith` and `startsWith` with case insensitivity. ```java Example example = Example.of(new Person("Jon", "Snow")); repo.findAll(example); ExampleMatcher matcher = ExampleMatcher.matching(). .withMatcher("firstname", endsWith()) .withMatcher("lastname", startsWith().ignoreCase()); Example example = Example.of(new Person("Jon", "Snow"), matcher); repo.count(example); ``` -------------------------------- ### Start Redis Cluster Nodes Source: https://github.com/spring-projects/spring-data-examples/blob/main/redis/cluster/readme.md This command starts the individual Redis cluster nodes. It uses the `create-cluster` utility script located in `redis/utils/create-cluster` to bring up six nodes (3 masters, 3 slaves). ```bash redis/utils/create-cluster $ ./create-cluster start Starting 30001 Starting 30002 Starting 30003 Starting 30004 Starting 30005 Starting 30006 ``` -------------------------------- ### Create and Initialize Redis Cluster Topology Source: https://github.com/spring-projects/spring-data-examples/blob/main/redis/cluster/readme.md This command initializes the Redis cluster by forming the cluster, performing hash slot allocation, and setting up master-replica relationships. This step is crucial and only needs to be done once after starting the nodes. ```bash redis/utils/create-cluster $ ./create-cluster create >>> Creating cluster >>> Performing hash slots allocation on 6 nodes... Using 3 masters: 127.0.0.1:30001 127.0.0.1:30002 127.0.0.1:30003 Adding replica 127.0.0.1:30004 to 127.0.0.1:30001 Adding replica 127.0.0.1:30005 to 127.0.0.1:30002 Adding replica 127.0.0.1:30006 to 127.0.0.1:30003 M: 10696916f57e58c5edce34127b23ca7af1b669a0 127.0.0.1:30001 slots:0-5460 (5461 slots) master M: 5b0e1b4cc87175326ba79d00ecfc6f5dbdb424a7 127.0.0.1:30002 slots:5461-10922 (5462 slots) master M: 5f3e978fb40b1d9c910d904ea19a0494b78668aa 127.0.0.1:30003 slots:10923-16383 (5461 slots) master S: d1717c418d03db93183ce2d791ba6f48be5cf028 127.0.0.1:30004 replicates 10696916f57e58c5edce34127b23ca7af1b669a0 S: c7dfcdb9cd1105e4251de51c4ade54de59bb063c 127.0.0.1:30005 replicates 5b0e1b4cc87175326ba79d00ecfc6f5dbdb424a7 S: 3219785a9145717f30648a27a2dd07359e9dd46f 127.0.0.1:30006 replicates 5f3e978fb40b1d9c910d904ea19a0494b78668aa Can I set the above configuration? (type 'yes' to accept): yes [OK] All nodes agree about slots configuration. >>> Check for open slots... >>> Check slots coverage... [OK] All 16384 slots covered. ``` -------------------------------- ### Build and Run Spring Data REST Application Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/starbucks/README.md Command to build and execute the Spring Boot application using Maven, which will start the embedded server and expose the REST API. ```Maven mvn spring-boot:run ``` -------------------------------- ### Perform Query-by-Example with Basic and Advanced Matching Source: https://github.com/spring-projects/spring-data-examples/blob/main/mongodb/query-by-example/README.md Illustrates how to create an `Example` object from an entity and use it with a repository's `findAll` method for basic QBE. Also shows how to use `ExampleMatcher` to define more complex matching rules like `endsWith` and `startsWith` with case insensitivity, and then apply it with `count`. ```java Example example = Example.of(new Person("Jon", "Snow")); repo.findAll(example); ExampleMatcher matcher = ExampleMatcher.matching(). .withMatcher("firstname", endsWith()) .withMatcher("lastname", startsWith().ignoreCase()); Example example = Example.of(new Person("Jon", "Snow"), matcher); repo.count(example); ``` -------------------------------- ### Install GraalVM and Native Image Tooling Source: https://github.com/spring-projects/spring-data-examples/blob/main/jpa/graalvm-native/README.adoc Instructions to download and install GraalVM and its native image tooling using SDKMAN! for Java development. ```Shell $> sdk install java .r17-grl $> gu install native-image ``` -------------------------------- ### Run Spring Boot Application with Maven Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/security/README.adoc This command starts the Spring Boot application using the Maven `spring-boot:run` goal. It compiles the project and launches the embedded server, making the REST API accessible on `localhost:8080`. ```bash $ mvn spring-boot:run ``` -------------------------------- ### Perform Query-by-Example with Spring Data JPA Source: https://github.com/spring-projects/spring-data-examples/blob/main/jpa/query-by-example/README.md This example demonstrates two ways to use Query-by-Example (QBE) with a Spring Data JPA repository. The first part shows a basic QBE using `Example.of()` to find all matching entities. The second part illustrates how to use `ExampleMatcher` to define more complex matching rules, such as `endsWith` and `startsWith` with case insensitivity, before executing a count query. ```java Example example = Example.of(new Person("Jon", "Snow")); repo.findAll(example); ExampleMatcher matcher = ExampleMatcher.matching(). .withMatcher("firstname", endsWith()) .withMatcher("lastname", startsWith().ignoreCase()); Example example = Example.of(new Person("Jon", "Snow"), matcher); repo.count(example); ``` -------------------------------- ### Log Output: Search Result Example Source: https://github.com/spring-projects/spring-data-examples/blob/main/mongodb/fragment-spi/README.adoc This log snippet displays an example of a search result, showing a movie entry retrieved after the data and index are available and a search query is performed. ```log INFO - ...mongodb.MovieRepositoryTests: 183 - Movie{id='66d6ee0937e07b74aa2939cc', ... ``` -------------------------------- ### Creating and Verifying a New Treasure Entity Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/multi-store/README.adoc This snippet demonstrates creating a new `Treasure` entity using a `curl` POST request to `/treasures` with a JSON payload. It then verifies the creation by performing a subsequent `curl` GET request to the newly created resource's URL, showcasing the full create and retrieve cycle for MongoDB-backed entities. ```bash $ curl -X POST -i -H "content-type:application/json" -d '{"name":"MacBook Pro", "description":"Tool of black magic"}' localhost:8080/treasures HTTP/1.1 201 Created Server: Apache-Coyote/1.1 Location: http://localhost:8080/treasures/53cee60a3004309b ``` -------------------------------- ### Creating and Verifying a New Person Entity Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/multi-store/README.adoc This snippet demonstrates the process of creating a new `Person` entity using a `curl` POST request to `/persons` with JSON payload. It then verifies the creation by performing a subsequent `curl` GET request to the newly created resource's URL, showcasing the full create and retrieve cycle for JPA-backed entities. ```bash $ curl -X POST -i -H "Content-Type:application/json" -d '{"firstName":"Greg", "lastName":"Turnquist"}' http://localhost:8080/persons HTTP/1.1 201 Created Server: Apache-Coyote/1.1 Location: http://localhost:8080/persons/3 Content-Length: 0 Date: Tue, 22 Jul 2014 22:26:17 GMT ``` ```bash $ curl http://localhost:8080/persons/3 ``` ```javascript { "firstName" : "Greg", "lastName" : "Turnquist", "_links" : { "self" : { "href" : "http://localhost:8080/persons/3" } } } ``` -------------------------------- ### Define Spring Data R2DBC Repository with Query-by-Example Source: https://github.com/spring-projects/spring-data-examples/blob/main/r2dbc/query-by-example/README.adoc Extends `ReactiveCrudRepository` and `ReactiveQueryByExampleExecutor` to enable Query-by-Example functionality for a `Person` entity in a Spring Data R2DBC repository. ```java interface PersonRepository extends ReactiveCrudRepository, ReactiveQueryByExampleExecutor { } ``` -------------------------------- ### Spring Boot Application for Multi-Store Data Repositories Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/multi-store/README.adoc This Java class defines the main Spring Boot application, `Application.java`, demonstrating how to configure and enable multiple Spring Data repositories (JPA and MongoDB) within a single application. It uses `@EnableJpaRepositories` and `@EnableMongoRepositories` with `basePackageClasses` to specify distinct packages for entity scanning. The `@PostConstruct` method initializes sample data for both `Person` (JPA) and `Treasure` (MongoDB) entities, showcasing the multi-store setup. ```java package example; // …import statements … @Configuration @EnableAutoConfiguration @EnableJpaRepositories @EnableMongoRepositories public class Application { private static final Logger log = LoggerFactory.getLogger(Application.class); public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Autowired PersonRepository personRepository; @Autowired TreasureRepository treasureRepository; @PostConstruct void checkitOut() { personRepository.save(new Person("Frodo", "Baggins")); personRepository.save(new Person("Bilbo", "Baggins")); for (Person person : personRepository.findAll()) { log.info("Hello " + person.toString()); } treasureRepository.deleteAll(); treasureRepository.save(new Treasure("Sting", "Made by the Elves")); treasureRepository.save(new Treasure("Sauron's ring", "One ring to rule them all")); for (Treasure treasure : treasureRepository.findAll()) { log.info("Found treasure " + treasure.toString()); } } } ``` -------------------------------- ### Define Repository with QueryByExampleExecutor Source: https://github.com/spring-projects/spring-data-examples/blob/main/mongodb/query-by-example/README.md Defines a Spring Data repository interface for `Person` entities, extending `CrudRepository` for basic CRUD operations and `QueryByExampleExecutor` to enable Query-by-Example capabilities. ```java interface PersonRepository extends CrudRepository, QueryByExampleExecutor { } ``` -------------------------------- ### Spring Data REST Resource JSON Example Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/multi-store/README.adoc Illustrates a partial JSON response for a resource, containing a 'description' field and a '_links' object with a 'self' HATEOAS link, typical for Spring Data REST applications. ```JSON "description" : "Tool of black magic", "_links" : { "self" : { "href" : "http://localhost:8080/treasures/53cee60a3004309b49465fbe" } } } ``` -------------------------------- ### Continuously Read Redis Stream Records (Imperative) Source: https://github.com/spring-projects/spring-data-examples/blob/main/redis/streams/README.md Illustrates setting up a continuous listener for a Redis Stream using the imperative API. It shows how to create a `StreamMessageListenerContainer` and register a `StreamListener` to process incoming messages from a specified stream starting from the beginning. ```Java @Autowired RedisConnectionFactory factory; StreamListener listener = (msg) -> { // ... }; StreamMessageListenerContainer container = StreamMessageListenerContainer.create(factory)); container.receive(StreamOffset.fromStart("my-stream"), listener); ``` -------------------------------- ### Define Reactive Repositories with Project Reactor Source: https://github.com/spring-projects/spring-data-examples/blob/main/mongodb/reactive/README.md Illustrates defining a reactive repository interface using Project Reactor's `Flux` and `Mono` types, extending `ReactiveCrudRepository`. It includes examples of finding by properties, using `@Query` annotations, accepting reactive type parameters for deferred execution, and using `@Tailable` cursors. ```java public interface ReactivePersonRepository extends ReactiveCrudRepository { Flux findByLastname(String lastname); @Query("{ 'firstname': ?0, 'lastname': ?1}") Mono findByFirstnameAndLastname(String firstname, String lastname); // Accept parameter inside a reactive type for deferred execution Flux findByLastname(Mono lastname); Mono findByFirstnameAndLastname(Mono firstname, String lastname); @Tailable // Use a tailable cursor Flux findWithTailableCursorBy(); } ``` -------------------------------- ### Retrieving All Treasure Entities via REST Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/multi-store/README.adoc This example illustrates how to retrieve all `Treasure` entities exposed by the Spring Data REST endpoint using a `curl` GET request to `/treasures`. The JSON response contains an embedded array of `Treasure` objects, including their `name`, `description`, and self-links, demonstrating successful retrieval from the MongoDB repository. ```bash $ curl http://localhost:8080/treasures ``` ```javascript { "_embedded" : { "treasures" : [ { "name" : "Sting", "description" : "Made by the Elves", "_links" : { "self" : { "href" : "http://localhost:8080/treasures/53cedae13004309b49465fbc" } } }, { "name" : "Sauron's ring", "description" : "One ring to rule them all", "_links" : { "self" : { "href" : "http://localhost:8080/treasures/53cedae13004309b49465fbd" } } } ] } } ``` -------------------------------- ### Conditional GET Request with If-None-Match Header Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/headers/README.adoc Shows how to perform a conditional GET request using the 'If-None-Match' header with an ETag. If the resource's ETag matches the provided value, the server returns a '304 Not Modified' status, indicating no change. ```bash $ curl http://localhost:8080/customers/1 -i -H "If-None-Match: 0" ``` ```http HTTP/1.1 304 Not Modified ``` -------------------------------- ### Configure Spring Boot Application Source: https://github.com/spring-projects/spring-data-examples/blob/main/elasticsearch/reactive/README.md This snippet shows a basic Spring Boot application configuration class, typically used to bootstrap a Spring Data Elasticsearch application. ```java @SpringBootApplication class ApplicationConfiguration {} ``` -------------------------------- ### Conditional GET Request with If-Modified-Since Header Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/headers/README.adoc Demonstrates how to issue a conditional GET request using the 'If-Modified-Since' header. If the resource has not been modified since the specified date, the server responds with a '304 Not Modified' status, saving bandwidth. ```bash $ curl http://localhost:8080/customers/1 -i -H "If-Modified-Since: Wed, 08 Apr 2015 17:24:20 GMT" ``` ```http HTTP/1.1 304 Not Modified ``` -------------------------------- ### Run Spring Data JDBC GraalVM Native Executable Source: https://github.com/spring-projects/spring-data-examples/blob/main/jdbc/graalvm-native/README.adoc Command to execute the compiled GraalVM native image directly from the console. The output demonstrates the application's startup and the results of CRUD functions invoked via a CommandLineRunner. ```Shell ./target/spring-data-jdbc-graalvm-native . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ ( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v3.0.0-SNAPSHOT) INFO 82562 --- [ main] e.s.j.g.GraalvmNativeApplication : Starting GraalvmNativeApplication using Java 17.0.4 with PID 82562 INFO 82562 --- [ main] e.s.j.g.GraalvmNativeApplication : Started GraalvmNativeApplication in 0.042 seconds (process running for 0.061) insertAuthors(): author1 = Author{name='Josh Long'} insertAuthors(): author2 = Author{name='Martin Kleppmann'} listAllAuthors(): author = Author{name='Josh Long'} Book{title='Reactive Spring'} ... ``` -------------------------------- ### Retrieving All Person Entities via REST Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/multi-store/README.adoc This example shows how to fetch all `Person` entities exposed by the Spring Data REST endpoint using a `curl` GET request to `/persons`. The JSON response contains an embedded array of `Person` objects, including their `firstName`, `lastName`, and self-links, demonstrating successful retrieval from the JPA repository. ```bash $ curl http://localhost:8080/persons ``` ```javascript { "_embedded" : { "persons" : [ { "firstName" : "Frodo", "lastName" : "Baggins", "_links" : { "self" : { "href" : "http://localhost:8080/persons/1" } } }, { "firstName" : "Bilbo", "lastName" : "Baggins", "_links" : { "self" : { "href" : "http://localhost:8080/persons/2" } } } ] } } ``` -------------------------------- ### Connect to Redis Cluster and Verify Nodes Source: https://github.com/spring-projects/spring-data-examples/blob/main/redis/cluster/readme.md This snippet demonstrates how to connect to the running Redis cluster using the `redis-cli` utility in cluster mode (`-c`) and then use the `cluster nodes` command to inspect the status and configuration of all nodes in the cluster. ```bash redis/src $ ./redis-cli -c -p 30001 127.0.0.1:30001> cluster nodes 106969... 127.0.0.1:30001 myself,master - 0 0 1 connected 0-5460 5b0e1b... 127.0.0.1:30002 master - 0 1450765112345 2 connected 5461-10922 5f3e97... 127.0.0.1:30003 master - 0 1450765112345 3 connected 10923-16383 d1717c... 127.0.0.1:30004 slave 106969... 0 1450765112345 4 connected c7dfcd... 127.0.0.1:30005 slave 5b0e1b... 0 1450765113050 5 connected 321978... 127.0.0.1:30006 slave 5f3e97... 0 1450765113050 6 connected ``` -------------------------------- ### Kotlin Spring Data MongoDB: Coroutines and Flow Support Source: https://github.com/spring-projects/spring-data-examples/blob/main/mongodb/kotlin/README.md Spring Data MongoDB provides robust support for Kotlin Coroutines and Flow, enabling efficient asynchronous and reactive programming patterns. These examples demonstrate how to use `awaitSingle()` for retrieving a single result and how to convert a collection to a Flow and then to a list within a `runBlocking` context. ```kotlin runBlocking { operations.find(Query(where("firstname").isEqualTo("Tyrion"))).awaitSingle() } ``` ```kotlin runBlocking { operations.findAll().asFlow().toList() } ``` -------------------------------- ### Retrieve All Employees from REST API (Unauthenticated) Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/security/README.adoc This `curl` command fetches the list of all employees from the `/employees` endpoint. It demonstrates an unauthenticated GET request to an endpoint that does not require security, returning a JSON array of employee objects. ```bash $ curl localhost:8080/employees ``` ```json { "_embedded" : { "employees" : [ { "firstName" : "Bilbo", "lastName" : "Baggins", "title" : "thief", "_links" : { "self" : { "href" : "http://localhost:8080/employees/1" } } }, { ... }] } } ``` -------------------------------- ### Activate Lazy Profile for Spring Data JPA Application Source: https://github.com/spring-projects/spring-data-examples/blob/main/jpa/deferred/README.adoc Command to run the Spring Data JPA example with the 'lazy' Spring profile activated, which enables deferred JPA initialization and lazy repository bootstrapping. ```bash $ java -jar -Dspring.profiles.active=lazy target/*.jar ``` -------------------------------- ### Define Reactive Repositories with RxJava 2 Source: https://github.com/spring-projects/spring-data-examples/blob/main/mongodb/reactive/README.md Shows how to define a reactive repository interface using RxJava 2's `Flowable`, `Maybe`, and `Single` types, extending `RxJava2CrudRepository`. It provides examples of finding by properties, using `@Query` annotations, accepting reactive type parameters for deferred execution, and using `@Tailable` cursors. ```java public interface RxJava2PersonRepository extends RxJava2CrudRepository { Flowable findByLastname(String lastname); @Query("{ 'firstname': ?0, 'lastname': ?1}") Maybe findByFirstnameAndLastname(String firstname, String lastname); // Accept parameter inside a reactive type for deferred execution Flowable findByLastname(Single lastname); Maybe findByFirstnameAndLastname(Single firstname, String lastname); @Tailable // Use a tailable cursor Flowable findWithTailableCursorBy(); } ``` -------------------------------- ### Define Repository for Query-by-Example in Spring Data JPA Source: https://github.com/spring-projects/spring-data-examples/blob/main/jpa/query-by-example/README.md This snippet shows how to define a Spring Data JPA repository interface that supports Query-by-Example (QBE). It extends `CrudRepository` for basic CRUD operations and `QueryByExampleExecutor` to enable QBE functionality for the `Person` entity. ```java public interface PersonRepository extends CrudRepository, QueryByExampleExecutor { } ``` -------------------------------- ### Cross-Origin Resource Sharing (CORS) Request Example Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/headers/README.adoc Illustrates a client-side JavaScript cross-origin request and the server's appropriate response. The server includes 'Access-Control-Allow-Origin' and 'Access-Control-Allow-Credentials' headers to permit the cross-origin access. ```bash $ curl 'http://localhost:8080/customers/' -i -H 'Origin: http://localhost' ``` ```http HTTP/1.1 200 OK Access-Control-Allow-Origin: http://localhost Vary: Origin Access-Control-Allow-Credentials: true ``` -------------------------------- ### Defining Reactive Repository with Project Reactor Source: https://github.com/spring-projects/spring-data-examples/blob/main/cassandra/reactive/README.md Illustrates how to define a reactive repository interface using `ReactiveCrudRepository` from Spring Data Cassandra, supporting Project Reactor's `Flux` and `Mono` types for query methods and deferred execution. ```java public interface ReactivePersonRepository extends ReactiveCrudRepository { Flux findByLastname(String lastname); @Query("SELECT * FROM person WHERE firstname = ?0 and lastname = ?1") Mono findByFirstnameAndLastname(String firstname, String lastname); // Accept parameter inside a reactive type for deferred execution Flux findByLastname(Mono lastname); Mono findByFirstnameAndLastname(Mono firstname, String lastname); } ``` -------------------------------- ### Run Spring Data JPA in Deferred Mode Source: https://github.com/spring-projects/spring-data-examples/blob/main/jpa/deferred/README.adoc This bash command demonstrates how to activate the 'deferred' Spring profile when starting the application. This profile enables background JPA initialization and deferred repository initialization, which helps optimize application startup time. ```bash $ java -jar -Dspring.profiles.active=deferred target/*.jar ``` -------------------------------- ### Access Spring Data REST Geolocation Search API Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/starbucks/README.md Example URL to directly access the geolocation search endpoint for coffee shops, specifying location coordinates and a search distance. ```HTTP http://localhost:8080/api/stores/search/findByAddressLocationNear?location=40.740337,-73.995146&distance=0.5miles ``` -------------------------------- ### Perform Full-Text Repository Queries in Spring Data MongoDB Source: https://github.com/spring-projects/spring-data-examples/blob/main/mongodb/text-search/README.md This example illustrates how to use derived finder methods within a Spring Data repository interface to execute full-text queries. It includes methods for paginating search results and for retrieving all matching documents sorted by their relevance score, utilizing `TextCriteria`. ```java interface BlogPostRepository extends CrudRepository { // page through results for full text query Page findBy(TextCriteria criteria, Pageable page); // find all matching documents and sort by relevance List findAllByOrderByScoreDesc(TextCriteria criteria); } ``` -------------------------------- ### Configure Spring Security Policy for REST Endpoints Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/security/README.adoc This snippet presents a `SecurityConfiguration` class that extends `WebSecurityConfigurerAdapter` to define the application's security policy. It configures in-memory user authentication with different roles, enables global method security, and sets up URL-level security for `/employees` endpoints, requiring `ROLE_ADMIN` for write operations while allowing GET requests. ```Java @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { /** * This section defines the user accounts which can be used for * authentication as well as the roles each user has. */ @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("greg").password("turnquist").roles("USER").and() .withUser("ollie").password("gierke").roles("USER", "ADMIN"); } /** * This section defines the security policy for the app. * - BASIC authentication is supported (enough for this REST-based demo) * - /employees is secured using URL security shown below * - CSRF headers are disabled since we are only testing the REST interface, * not a web one. * * NOTE: GET is not shown which defaults to permitted. */ @Override protected void configure(HttpSecurity http) throws Exception { http .httpBasic().and() .authorizeRequests() .antMatchers(HttpMethod.POST, "/employees").hasRole("ADMIN") .antMatchers(HttpMethod.PUT, "/employees/**").hasRole("ADMIN") .antMatchers(HttpMethod.PATCH, "/employees/**").hasRole("ADMIN").and() .csrf().disable(); } } ``` -------------------------------- ### Access Spring Data REST HAL Browser Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/starbucks/README.md URL to access the HAL browser, which is integrated into the application to facilitate discovery and exploration of the exposed REST API. ```HTTP http://localhost:8080/api ``` -------------------------------- ### Using ReactiveCassandraTemplate for Data Operations Source: https://github.com/spring-projects/spring-data-examples/blob/main/cassandra/reactive/README.md Demonstrates basic reactive data access operations using `ReactiveCassandraTemplate` and Project Reactor's `Mono` and `Flux` types. It shows how to insert multiple `Person` objects and select them based on a criteria. ```java template.insert(Flux.just(new Person("Walter", "White", 50), new Person("Skyler", "White", 45), new Person("Saul", "Goodman", 42), new Person("Jesse", "Pinkman", 27))); Flux flux = template.select(select() .from("person") .where(eq("lastname", "White")), Person.class); ``` -------------------------------- ### Access Spring Data REST Root API Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/starbucks/README.md Command to access the root resource of the RESTful API using curl, allowing traversal of hypermedia links to discover available resources. ```Shell curl http://localhost:8080/api ``` -------------------------------- ### Spring Data JPA Default Bootstrap Mode Log Source: https://github.com/spring-projects/spring-data-examples/blob/main/jpa/deferred/README.adoc This log output illustrates the synchronous JPA and Spring Data repository bootstrap process when running in the default mode. It shows the sequence of initialization steps, including repository scanning, HikariCP setup, Hibernate initialization, and the total application startup time. ```bash 2018-08-16 14:38:49.540 INFO 44538 --- [ main] example.Application : Starting Application v2.0.0.BUILD-SNAPSHOT on … 2018-08-16 14:38:49.544 INFO 44538 --- [ main] example.Application : No active profile set, falling back to default profiles: default 2018-08-16 14:38:51.034 INFO 44538 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode. 2018-08-16 14:38:53.433 INFO 44538 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 2390ms. Found 2000 repository interfaces. 2018-08-16 14:38:54.444 INFO 44538 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... 2018-08-16 14:38:54.447 WARN 44538 --- [ main] com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=org.hsqldb.jdbcDriver was not found, trying direct instantiation. 2018-08-16 14:38:54.773 INFO 44538 --- [ main] com.zaxxer.hikari.pool.PoolBase : HikariPool-1 - Driver does not support get/set network timeout for connections. (feature not supported) 2018-08-16 14:38:54.776 INFO 44538 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. 2018-08-16 14:38:55.068 INFO 44538 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default ...] <1> 2018-08-16 14:38:55.144 INFO 44538 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.5.Final} 2018-08-16 14:38:55.146 INFO 44538 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found 2018-08-16 14:38:55.473 INFO 44538 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final} 2018-08-16 14:38:55.875 INFO 44538 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.HSQLDialect 2018-08-16 14:39:00.977 INFO 44538 --- [ main] o.h.t.schema.internal.SchemaCreatorImpl : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@60169e0f' 2018-08-16 14:39:00.985 INFO 44538 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2018-08-16 14:39:23.378 INFO 44538 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 2018-08-16 14:39:23.504 INFO 44538 --- [ main] example.Application : Started Application in 34.423 seconds (JVM running for 34.899) ``` -------------------------------- ### Continuously Read Redis Stream Records (Reactive) Source: https://github.com/spring-projects/spring-data-examples/blob/main/redis/streams/README.md Demonstrates how to set up a continuous receiver for a Redis Stream using the reactive API. It shows creating a `StreamReceiver` and subscribing to a stream to process incoming messages reactively. ```Java @Autowired ReactiveRedisConnectionFactory factory; StreamReceiver receiver = StreamReceiver.create(factory)); container.receive(StreamOffset.fromStart("my-stream")) .doOnNext((msg) -> { // ... }) .subscribe(); ``` -------------------------------- ### Access Spring Data REST Web UI Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/starbucks/README.md URL to access the custom web user interface provided by the application, which displays search results on a Google Map. ```HTTP http://localhost:8080 ``` -------------------------------- ### Consume MongoDB Change Streams Reactively with Flux Source: https://github.com/spring-projects/spring-data-examples/blob/main/mongodb/change-streams/README.md This example shows how to consume MongoDB Change Stream events using a reactive `Flux`. It filters for 'insert' operations on the 'person' collection and prints the first name from the event body upon reception, demonstrating a non-blocking approach to event handling. ```Java Flux changeStream = reactiveTemplate .changeStream(newAggregation(match(where("operationType").is("insert"))), Person.class, ChangeStreamOptions.empty(), "person"); changeStream.doOnNext(event -> System.out.println("Hello " + event.getBody().getFirstname())) .subscribe(); ``` -------------------------------- ### Defining Reactive Repository with RxJava 1 Source: https://github.com/spring-projects/spring-data-examples/blob/main/cassandra/reactive/README.md Shows how to define a reactive repository interface using `RxJava1CrudRepository` from Spring Data Cassandra, supporting RxJava 1's `Observable` and `Single` types for query methods and deferred execution. ```java public interface RxJava1PersonRepository extends RxJava1CrudRepository { Observable findByLastname(String lastname); @Query("SELECT * FROM person WHERE firstname = ?0 and lastname = ?1") Single findByFirstnameAndLastname(String firstname, String lastname); // Accept parameter inside a reactive type for deferred execution Observable findByLastname(Single lastname); Single findByFirstnameAndLastname(Single firstname, String lastname); } ``` -------------------------------- ### Log Output: Data Loading and Index Creation Progress Source: https://github.com/spring-projects/spring-data-examples/blob/main/mongodb/fragment-spi/README.adoc This log snippet shows the progress of loading movie data into the `test.movies` collection and the subsequent creation of a vector index named 'plot_vector_index' within a MongoDB Atlas instance during the sample's execution. ```log INFO - com.example.data.mongodb.Movies: 73 - Loading movies from class path resource [mflix.embedded_movies.json.gz] INFO - com.example.data.mongodb.Movies: 90 - Created 420 movies in test.movies INFO - com.example.data.mongodb.Movies: 65 - creating vector index INFO - com.example.data.mongodb.Movies: 68 - index 'plot_vector_index' created ``` -------------------------------- ### Run Spring Data JDBC Immutables Tests Source: https://github.com/spring-projects/spring-data-examples/blob/main/jdbc/immutables/README.adoc To execute the tests for the Spring Data JDBC with Immutables example, use the Maven test command. This command will also automatically trigger the Immutables code generator if necessary. ```bash $ mvn test ``` -------------------------------- ### Perform Reactive Elasticsearch Operations Source: https://github.com/spring-projects/spring-data-examples/blob/main/elasticsearch/reactive/README.md Demonstrates how to use `ReactiveElasticsearchOperations` to execute a `CriteriaQuery` and retrieve a `Flux` of `Conference` objects reactively. It shows dependency injection and a basic search operation. ```java @Autowired ReactiveElasticsearchOperations operations; // ... CriteriaQuery query = new CriteriaQuery("keywords").contains("java"); Flux result = operations.find(query, Conference.class); ``` -------------------------------- ### Query a GridFS file by metadata in Spring Data MongoDB Source: https://github.com/spring-projects/spring-data-examples/blob/main/mongodb/gridfs/README.md Demonstrates how to query for a GridFSDBFile based on its associated metadata using GridFsOperations. ```java GridFSDBFile gridFsFile = gridFsOperations.findOne(query(whereMetaData("firstName").is("Hardy"))); ``` -------------------------------- ### JavaScript Starbucks Store Search and Map Initialization Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/starbucks/src/main/resources/templates/index.html This JavaScript code initializes the Starbucks store finder application, handling map setup, user location input, and performing store searches using a URI template. It dynamically updates the map with markers for found stores and manages existing markers. ```JavaScript (function () { "use strict"; function initApp() { function handleSearchResult(searchResponse) { } window.starbucks = { ui: { markers: [], map: null }, performStoreSearch: function () { // Maps enabled (online)? if (!starbucks.ui.map) { return; } // Get location var location = $("#location").val(); // Center map var coordinate = { lat: parseFloat(location.split(",")[0]), lng: parseFloat(location.split(",")[1]) } starbucks.ui.map.setCenter(coordinate); new google.maps.Marker({ position: coordinate, map: starbucks.ui.map }); // Expand template and execute search var template = new URITemplate($("#map").attr("data-uri")); $.get(template.expand({ "location": location, "distance": $("#distance").val(), "size": 100, "page": 0 }), function(response) { while (starbucks.ui.markers.length) { starbucks.ui.markers.pop().setMap(null); } // Create marker for store response._embedded["stores"].forEach(function (store) { starbucks.ui.markers.push(new google.maps.Marker({ position: { lat: store.address.location.y, lng: store.address.location.x }, map: starbucks.ui.map })); }); }) }, init: function() { starbucks.ui.map = new google.maps.Map($("#map")[0], { zoom: 14 }); starbucks.performStoreSearch(); } }; window.starbucks.init(); } $(initApp); })(); ``` -------------------------------- ### Discovering Root REST Resources with curl Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/multi-store/README.adoc This snippet demonstrates how to query the root of the Spring Data REST application using `curl` to discover the available top-level resources. The JSON response lists hypermedia links to the `persons` and `treasures` endpoints, confirming that both JPA and MongoDB repositories are successfully exposed. ```bash $ curl http://localhost:8080 ``` ```javascript { "_links" : { "persons" : { "href" : "http://localhost:8080/persons" }, "treasures" : { "href" : "http://localhost:8080/treasures" } } } ``` -------------------------------- ### Define Reactive Repository Interface for Spring Data Couchbase Source: https://github.com/spring-projects/spring-data-examples/blob/main/couchbase/reactive/README.md Demonstrates how to define a reactive repository interface using Spring Data Couchbase's ReactiveCrudRepository. This interface extends Spring Data's reactive capabilities, allowing for non-blocking data operations. It includes examples of finding a single entity by IATA code (Mono) and finding all entities (Flux). ```java public interface ReactiveAirlineRepository extends ReactiveCrudRepository { Mono findByIata(String code); Flux findAllBy(); } ``` -------------------------------- ### Compile Spring Data JDBC Application to Native Image with Maven Source: https://github.com/spring-projects/spring-data-examples/blob/main/jdbc/graalvm-native/README.adoc Command to compile the Spring Data JDBC application into a GraalVM native image using Maven. It leverages a dedicated 'native' profile to trigger the native image creation process. ```Shell maven clean package -P native ``` -------------------------------- ### Configure Spring Data Redis with Lettuce Connection Factory Source: https://github.com/spring-projects/spring-data-examples/blob/main/redis/repositories/README.md This Java configuration class sets up Spring Data Redis using `LettuceConnectionFactory` to connect to Redis on its default port. It demonstrates the use of `@EnableRedisRepositories` to enable repository support and defines a `RedisTemplate` bean for interacting with Redis, which handles object/hash conversion. ```java @Configuration @EnableRedisRepositories class AppConfig { @Bean RedisConnectionFactory connectionFactory() { return new LettuceConnectionFactory(); } @Bean RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); return template; } } ``` -------------------------------- ### Stop Redis Cluster Nodes Source: https://github.com/spring-projects/spring-data-examples/blob/main/redis/cluster/readme.md This command gracefully shuts down all running Redis cluster nodes. It uses the `create-cluster` utility script with the `stop` argument. ```bash redis/utils/create-cluster $ ./create-cluster stop ``` -------------------------------- ### Perform Reactive Data Operations with ReactiveMongoTemplate Source: https://github.com/spring-projects/spring-data-examples/blob/main/mongodb/reactive/README.md Demonstrates basic reactive data access operations using `ReactiveMongoTemplate` and Project Reactor's `Mono` and `Flux` types. It shows how to insert multiple `Person` objects and find them based on criteria. ```java template.insertAll(Arrays.asList(new Person("Walter", "White", 50), new Person("Skyler", "White", 45), new Person("Saul", "Goodman", 42), new Person("Jesse", "Pinkman", 27))); Flux flux = template.find(Query.query(Criteria.where("lastname").is("White")), Person.class); ``` -------------------------------- ### Kotlin Spring Data MongoDB: Value Defaulting on Entity Construction Source: https://github.com/spring-projects/spring-data-examples/blob/main/mongodb/kotlin/README.md Kotlin allows defaulting for constructor and method arguments, enabling the use of substitute values if a field in the document is absent or null. Spring Data inspects Kotlin types and uses the appropriate constructor. This example demonstrates inserting a document without a 'firstname' and verifying that the default 'Walter' is applied upon retrieval. ```kotlin data class Person (@Id val id: String?, val firstname: String? = "Walter", val lastname: String) operations.insert().inCollection("person").one(Document("lastname", "White")) val walter = operations.findOne(query(where("lastname").isEqualTo("White")), "person") assertThat(walter.firstname).isEqualTo("Walter") ``` -------------------------------- ### Configure Redis Sentinel Support in Spring Data Redis Source: https://github.com/spring-projects/spring-data-examples/blob/main/redis/sentinel/README.md This Java configuration class sets up a RedisConnectionFactory using Lettuce and RedisSentinelConfiguration. It defines a master node 'mymaster' and three sentinel instances running on localhost, enabling Spring Data Redis to connect to a Redis Sentinel cluster. ```java @Configuration public class RedisSentinelApplicationConfig { static final RedisSentinelConfiguration SENTINEL_CONFIG = new RedisSentinelConfiguration().master("mymaster") // .sentinel("localhost", 26379) // .sentinel("localhost", 26380) // .sentinel("localhost", 26381); @Bean public RedisConnectionFactory connectionFactory() { return new LettuceConnectionFactory(sentinelConfig(), LettuceClientConfiguration.defaultConfiguration()); } @Bean public RedisSentinelConfiguration sentinelConfig() { return SENTINEL_CONFIG; } } ``` -------------------------------- ### Define and Use Reactive Elasticsearch Repository Source: https://github.com/spring-projects/spring-data-examples/blob/main/elasticsearch/reactive/README.md Illustrates defining a reactive repository interface extending `ReactiveCrudRepository` for `Conference` entities, including a custom query method. It then shows how to inject and use this repository to find conferences by keyword reactively. ```java interface ConferenceRepository extends ReactiveCrudRepository { Flux findAllByKeywordsContains(String keyword); } // ... @Autowired ConferenceRepository repository; // ... Flux result = repository.findAllByKeywordsContains("java"); ``` -------------------------------- ### Query a GridFS file by name in Spring Data MongoDB Source: https://github.com/spring-projects/spring-data-examples/blob/main/mongodb/gridfs/README.md Illustrates how to use GridFsOperations to find a GridFSDBFile by its filename. ```java GridFSDBFile gridFsFile = gridFsOperations.findOne(query(whereFilename().is("myFile1.txt"))); ``` -------------------------------- ### Store a file using Spring Data MongoDB GridFS Source: https://github.com/spring-projects/spring-data-examples/blob/main/mongodb/gridfs/README.md Demonstrates how to use GridFsOperations to store an InputStream as a file in MongoDB GridFS. ```java InputStream is = ... gridFsOperations.store(is, "myFile1.txt"); ``` -------------------------------- ### Retrieve Items with User-Level Credentials (Successful) Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/security/README.adoc This `curl` command successfully fetches the list of items from the `/items` endpoint using 'USER' level credentials (`greg:turnquist`). The request returns a `200 OK` status with the item data, demonstrating that user-level authentication is sufficient to read from this secured repository. ```bash $ curl localhost:8080/items -u greg:turnquist ``` ```json { "_embedded" : { "items" : [ { "description" : "Sting", "_links" : { "self" : { "href" : "http://localhost:8080/items/1" } } }, { "description" : "the one ring", "_links" : { "self" : { "href" : "http://localhost:8080/items/2" } } } ] } } ``` -------------------------------- ### Value Defaulting on Kotlin Entity Construction Source: https://github.com/spring-projects/spring-data-examples/blob/main/cassandra/kotlin/README.md Kotlin allows defaulting for constructor and method arguments, providing substitute values if a field in the document is absent or null. Spring Data inspects Kotlin types to use the appropriate constructor for entity creation. ```kotlin @Table data class Person(@PrimaryKeyColumn(type = PrimaryKeyType.PARTITIONED) val firstname: String? = "", val lastname: String = "White") operations.cqlOperations.execute(QueryBuilder.insertInto("person").value("firstname", "Walter")) val person = operations.query() .matching(query(where("firstname").isEqualTo("Walter"))) .firstValue()!! assertThat(person.lastname).isEqualTo("White") ``` -------------------------------- ### Configure Spring Data Redis for Cluster Connection Source: https://github.com/spring-projects/spring-data-examples/blob/main/redis/cluster/readme.md This snippet shows how to configure Spring Data Redis to connect to a Redis cluster. It specifies the initial set of known cluster nodes in the `application.properties` file, which will be used by auto-configuration. ```properties spring.redis.cluster.nodes[0]=127.0.0.1:30001 spring.redis.cluster.nodes[1]=127.0.0.1:30002 spring.redis.cluster.nodes[2]=127.0.0.1:30003 ``` -------------------------------- ### Attempt to Create Employee with User-Level Credentials (Forbidden) Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/security/README.adoc This `curl` command attempts to create a new employee using a POST request to `/employees` with 'USER' level credentials (`greg:turnquist`). The request is denied with a `403 Forbidden` status, indicating that while authenticated, the user lacks sufficient authorization to perform this operation. ```bash $ curl -X POST -d '{"firstName": "Saruman", "lastName": "the evil one", "title": "the White"}' localhost:8080/employees -u greg:turnquist ``` ```json {"timestamp":1412958491870,"status":403,"error":"Forbidden","message":"Access is denied","path":"/employees"} ``` -------------------------------- ### Querying Customers with Querydsl in Spring Data MongoDB (Imperative) Source: https://github.com/spring-projects/spring-data-examples/blob/main/mongodb/querydsl/README.md This snippet demonstrates imperative querying using Querydsl with Spring Data MongoDB. It shows how to define a repository extending `CrudRepository` and `QuerydslPredicateExecutor`, and then execute a type-safe query against the `Customer` entity using a generated Q-class. ```java interface CustomerQuerydslRepository extends CrudRepository, QuerydslPredicateExecutor { } @Autowired CustomerQuerydslRepository repository; // ... List result = repository.findAll(QCustomer.customer.lastname.eq("Matthews")); ``` -------------------------------- ### Define Item Domain Object Source: https://github.com/spring-projects/spring-data-examples/blob/main/rest/security/README.adoc This snippet defines the `Item` domain object, similar to `Employee`, as a JPA-annotated POJO. It includes an `id` and a `description` field, serving as a basic entity for the Spring Data REST application. ```Java @Entity public class Item { private @Id @GeneratedValue Long id; private String description; … } ``` -------------------------------- ### Define Spring Data LDAP Person Repository Interface Source: https://github.com/spring-projects/spring-data-examples/blob/main/ldap/example/README.md Defines a Spring Data LDAP repository interface for `Person` entities, extending `CrudRepository`. It includes custom methods for searching by `uid` and `lastname` prefix, demonstrating basic interaction for searching, creating, and modifying objects in an LDAP repository. ```java public interface PersonRepository extends CrudRepository { List findByUid(String uid); List findByLastnameStartsWith(String prefix); } ```