### Query by Example with a simple probe Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/query-by-example.adoc Create a domain object with criteria, create an Example, and execute a query through the repository. Null fields are ignored. ```APIDOC ## Query by Example with a simple probe ### Description Create a domain object with criteria (null fields ignored), create an Example, and execute a query through the repository. Use `findOne` for a single item. ### Usage - Create a domain object with criteria (null fields ignored). - Create an `Example` from the domain object. - Execute query through the repository (use `findOne` for a single item). ### Example ```java // Create a domain object with criteria (null fields ignored) Employee employee = new Employee(); employee.setName("Frodo"); // Create an Example Example example = Example.of(employee); // Execute query through the repository repository.findOne(example); ``` ### Notes - This queries based on the `Employee` object's `name` field being equal to `Frodo`. - `null` fields are ignored. ``` -------------------------------- ### Create a simple probe with Example Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/query-by-example.adoc Creates an Example from a domain object, ignoring null fields. The query matches the Employee's name field equal to 'Frodo'. ```java include::example$r2dbc/QueryByExampleTests.java[tag=example] ``` -------------------------------- ### Create main application class (included from example) Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/getting-started.adoc The main application class is included from an external example file. The actual code is not shown on this page. ```java include::example$r2dbc/R2dbcApp.java[tag=class] ``` -------------------------------- ### Create Person class (included from example) Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/getting-started.adoc The Person class is included from an external example file. The actual code is not shown on this page. ```java include::example$r2dbc/Person.java[tags=class] ``` -------------------------------- ### Query by Example with custom ExampleMatcher Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/query-by-example.adoc Create a custom ExampleMatcher to match on all fields, use wildcards, match nulls, and ignore fields. ```APIDOC ## Query by Example with custom ExampleMatcher ### Description Create a custom `ExampleMatcher` to customize matching behavior: match on ALL fields (or ANY with `matchingAny()`), use wildcards, match nulls, and ignore fields. ### Usage - Create a custom `ExampleMatcher` that matches on ALL fields (use `matchingAny()` to match on *ANY* fields). - For the `name` field, use a wildcard that matches against the end of the field. - Match columns against `null` (note that `NULL` doesn't equal `NULL` in relational databases). - Ignore the `role` field when forming the query. - Plug the custom `ExampleMatcher` into the probe. ### Example ```java // Create a custom ExampleMatcher ExampleMatcher matcher = ExampleMatcher.matchingAll() .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.endsWith()) .withIncludeNullValues() .withIgnorePaths("role"); // Create an Example with the matcher Example example = Example.of(employee, matcher); ``` ### Notes - It's also possible to apply a `withTransform()` against any property to transform a property before forming the query (e.g., `toUpperCase()` on a `String`-based property). ``` -------------------------------- ### Example debug output from running the application Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/getting-started.adoc Sample debug output showing the SQL statements executed and the resulting Person object. ```text 2018-11-28 10:47:03,893 DEBUG ework.core.DatabaseClient: 310 - Executing SQL statement [CREATE TABLE person( id VARCHAR(255) PRIMARY KEY, name VARCHAR(255), age INT )] 2018-11-28 10:47:04,074 DEBUG ework.core.DatabaseClient: 908 - Executing SQL statement [INSERT INTO person (id, name, age) VALUES($1, $2, $3)] 2018-11-28 10:47:04,092 DEBUG ework.core.DatabaseClient: 575 - Executing SQL statement [SELECT id, name, age FROM person] 2018-11-28 10:47:04,436 INFO org.spring.r2dbc.example.R2dbcApp: 43 - Person [id='joe', name='Joe', age=34] ``` -------------------------------- ### Java: Retrieve all SWCharacter objects with DatabaseClient Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/kotlin.adoc Java example using DatabaseClient to fetch all SWCharacter objects. The result is a Flux. ```java Flux characters = client.select().from(SWCharacter.class).fetch().all(); ``` -------------------------------- ### @Modifying Query Example (include directive) Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/query-methods.adoc Shows an example of a modifying query using @Modifying. The actual code is included from an external file via an include directive and is not displayed on this page. ```java include::example$r2dbc/PersonRepository.java[tags=atModifying] ``` -------------------------------- ### ReactivePersonRepository with query methods Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/query-methods.adoc Example repository interface demonstrating various query method patterns, including derived queries, reactive parameter support, Pageable usage, single result retrieval, and @Query annotated queries. ```java interface ReactivePersonRepository extends ReactiveSortingRepository { Flux findByFirstname(String firstname); <1> Flux findByFirstname(Publisher firstname); <2> Flux findByFirstnameOrderByLastname(String firstname, Pageable pageable); <3> Mono findByFirstnameAndLastname(String firstname, String lastname); <4> Mono findFirstByLastname(String lastname); <5> @Query("SELECT * FROM person WHERE lastname = :lastname") Flux findByLastname(String lastname); <6> @Query("SELECT firstname, lastname FROM person WHERE lastname = $1") Mono findFirstByLastname(String lastname); <7> } ``` -------------------------------- ### Run integration tests with a real database Source: https://github.com/spring-projects/spring-data-relational/blob/main/spring-data-jdbc/README.adoc Executes unit tests and integration tests against a specific database. Requires a local Docker installation. Replace with one of: hsql, mysql, mariadb, postgres, mssql, oracle, db2. ```bash mvn verify -Dspring.profiles.active= ``` -------------------------------- ### Spring Data R2DBC Repository Example Source: https://github.com/spring-projects/spring-data-relational/blob/main/README.adoc Quick teaser of an application using Spring Data R2DBC Repositories in Java. Includes a PersonRepository with reactive @Query methods and a MyService that uses the repository. ```java interface PersonRepository extends ReactiveCrudRepository { @Query("SELECT * FROM person WHERE lastname = :lastname") Flux findByLastname(String lastname); @Query("SELECT * FROM person WHERE firstname LIKE :firstname") Flux findByFirstnameLike(String firstname); } @Service class MyService { private final PersonRepository repository; public MyService(PersonRepository repository) { this.repository = repository; } public Flux doWork() { Person person = new Person(); person.setFirstname("Jens"); person.setLastname("Schauder"); repository.save(person); Mono deleteAll = repository.deleteAll(); Flux lastNameResults = repository.findByLastname("Schauder"); Flux firstNameResults = repository.findByFirstnameLike("Je%"); return lastNameResults.concatWith(firstNameResults); } } ``` -------------------------------- ### Customized object construction with @PersistenceConstructor Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/partials/mapping.adoc Example of a class with a constructor that can be annotated with @PersistenceConstructor for customized object construction. Parameter names must be present in the class files (compile with debug info or -parameters). ```java class OrderItem { private @Id final String id; private final int quantity; private final double unitPrice; OrderItem(String id, int quantity, double unitPrice) { this.id = id; this.quantity = quantity; this.unitPrice = unitPrice; } // getters/setters omitted } ``` -------------------------------- ### Kotlin: Retrieve all SWCharacter objects with reified generics Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/kotlin.adoc Kotlin example using reified generics to fetch all SWCharacter objects. Two equivalent syntaxes are shown, both returning Flux. ```kotlin val characters = client.select().from().fetch().all() // or (both are equivalent) val characters : Flux = client.select().from().fetch().all() ``` -------------------------------- ### Spring Data JDBC Repository Example Source: https://github.com/spring-projects/spring-data-relational/blob/main/README.adoc Quick teaser of an application using Spring Data JDBC Repositories in Java. Includes a Person entity, a PersonRepository with @Query methods, a MyService that uses the repository, and an ApplicationConfig with @EnableJdbcRepositories. ```java @Table public class Person { @Id private Long id; private String firstname; private String lastname; // getters and setters } interface PersonRepository extends CrudRepository { @Query("SELECT * FROM person WHERE lastname = :lastname") List findByLastname(String lastname); @Query("SELECT * FROM person WHERE firstname LIKE :firstname") List findByFirstnameLike(String firstname); } @Service class MyService { private final PersonRepository repository; public MyService(PersonRepository repository) { this.repository = repository; } public void doWork() { repository.deleteAll(); Person person = new Person(); person.setFirstname("Jens"); person.setLastname("Schauder"); repository.save(person); List lastNameResults = repository.findByLastname("Schauder"); List firstNameResults = repository.findByFirstnameLike("Je%"); } } @Configuration @EnableJdbcRepositories class ApplicationConfig extends AbstractJdbcConfiguration { @Bean public DataSource dataSource() { return …; } @Bean public NamedParameterJdbcTemplate namedParameterJdbcTemplate(DataSource dataSource) { return new NamedParameterJdbcTemplate(dataSource); } } ``` -------------------------------- ### Optimistic Locking with @Version Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/entity-persistence.adoc Demonstrates how to use the @Version annotation to detect concurrent modifications. The example shows an initial insert, a successful update that increments the version, and a subsequent update attempt on a stale entity that triggers an OptimisticLockingFailureException. ```java @Table class Person { @Id Long id; String firstname; String lastname; @Version Long version; } R2dbcEntityTemplate template = …; Mono daenerys = template.insert(new Person("Daenerys")); <1> Person other = template.select(Person.class) .matching(query(where("id").is(daenerys.getId()))) .first().block(); <2> daenerys.setLastname("Targaryen"); template.update(daenerys); <3> template.update(other).subscribe(); // emits OptimisticLockingFailureException <4> ``` -------------------------------- ### Insert statement enriched with Id value Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/partials/sequences.adoc The fetched identifier value is included in the INSERT statement's VALUES clause. This example shows the SQL for inserting into the my_entity table. ```sql INSERT INTO "my_entity"("id", "name") VALUES(?, ?); ``` -------------------------------- ### Define a global listener for BeforeSaveEvent (Java) Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/events.adoc Defines a Spring bean that listens for BeforeSaveEvent of any aggregate root. The listener logs the entity before the aggregate gets saved. Use this for global event handling across all domain types. ```java @Bean ApplicationListener> loggingSaves() { return event -> { Object entity = event.getEntity(); LOG.info("{} is getting saved.", entity); }; } ``` -------------------------------- ### Generated Liquibase change log for Person Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/schema-support.adoc Example Liquibase change log generated from the Person entity. Column types are computed from an object implementing SqlTypeMapping, and nullability is inferred from the property type (false for primitive Java types). ```yaml databaseChangeLog: - changeSet: id: '1685969572426' author: Spring Data Relational objectQuotingStrategy: LEGACY changes: - createTable: columns: - column: autoIncrement: true constraints: nullable: false primaryKey: true name: id type: BIGINT - column: constraints: nullable: true name: first_name type: VARCHAR(255 BYTE) - column: constraints: nullable: true name: last_name type: VARCHAR(255 BYTE) - column: constraints: nullable: true name: birthday type: DATE - column: constraints: nullable: false name: active type: TINYINT tableName: person ``` -------------------------------- ### Use a SpEL in a query Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/query-methods.adoc Example of using SpEL in a @Query annotation to dynamically reference a table name. The SpEL expression is evaluated once before the first execution using a StandardEvaluationContext with variables tableName and qualifiedTableName. ```java @Query("SELECT * FROM #{tableName} WHERE id = :id") Person findWithSpEL(PersonRef person); ``` -------------------------------- ### Entity with Id generation from a Sequence Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/partials/sequences.adoc Annotate an @Id property with @Sequence to fetch its initial value from a database sequence. The sequence name and schema are specified in the annotation. This example uses a Long id field. ```java @Table class MyEntity { @Id @Sequence( sequence = "my_seq", schema = "public" ) private Long id; // … } ``` -------------------------------- ### Maven Snapshot Dependency and Repository for spring-data-jdbc Source: https://github.com/spring-projects/spring-data-relational/blob/main/README.adoc Use the Maven snapshot repository to get the latest snapshots of the upcoming major version. Declare the dependency with version ${version}-SNAPSHOT and add the spring-snapshot repository. ```xml org.springframework.data spring-data-jdbc ${version}-SNAPSHOT spring-snapshot Spring Snapshot Repository https://repo.spring.io/snapshot ``` -------------------------------- ### Resulting SQL query for MySQL dialect with pessimistic read lock Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/transactions.adoc Example of the SQL query generated by @Lock with pessimistic read lock for MySQL dialect. The exact query is 'Select * from user u where u.lastname = lastname LOCK IN SHARE MODE'. ```sql Select * from user u where u.lastname = lastname LOCK IN SHARE MODE ``` -------------------------------- ### Example domain object with @Table annotation Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/mapping.adoc Annotate domain objects with @Table to enable classpath scanning and metadata pre-processing. The @Id annotation marks the primary key property. Without @Table, mapping still works but incurs a performance hit on first store. ```java package com.mycompany.domain; @Table public class Person { @Id private Long id; private Integer ssn; private String firstName; private String lastName; } ``` -------------------------------- ### Build and Generate Documentation with Maven Source: https://github.com/spring-projects/spring-data-relational/blob/main/README.adoc Run this Maven command to build the project and generate the Antora documentation. The build also runs tests unless skipped. The generated documentation is available at spring-data-jdbc-distribution/target/antora/site/index.html. ```bash $ ./mvnw clean install -Pantora ``` -------------------------------- ### Use custom ExampleMatcher for flexible matching Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/query-by-example.adoc Creates a custom ExampleMatcher that matches on all fields, uses a wildcard for the name field, matches null columns, ignores the role field, and plugs the matcher into the probe. ```java include::example$r2dbc/QueryByExampleTests.java[tag=example-2] ``` -------------------------------- ### Run Integration Tests Against All Databases Source: https://github.com/spring-projects/spring-data-relational/blob/main/README.adoc Runs integration tests against all supported databases by activating the 'all-dbs' Maven profile. Requires an appropriate container-license-acceptance.txt on the classpath. ```bash ./mvnw clean install -Pall-dbs ``` -------------------------------- ### Build Spring Data with Maven Wrapper Source: https://github.com/spring-projects/spring-data-relational/blob/main/README.adoc Builds the project from source using the Maven wrapper. Requires JDK 17. ```bash $ ./mvnw clean install ``` -------------------------------- ### Run fast tests with Maven Source: https://github.com/spring-projects/spring-data-relational/blob/main/spring-data-jdbc/README.adoc Executes unit tests and integration tests using an in-memory database. ```bash mvn test ``` -------------------------------- ### Configure R2DBC mapping support with AbstractR2dbcConfiguration Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/mapping.adoc Java-based configuration class extending AbstractR2dbcConfiguration to set up R2DBC mapping support. Requires implementing connectionFactory() and optionally overriding getCustomConverters() to register custom converters. ```java @Configuration public class MyAppConfig extends AbstractR2dbcConfiguration { public ConnectionFactory connectionFactory() { return ConnectionFactories.get("r2dbc:…"); } // the following are optional @Override protected List getCustomConverters() { return List.of(new PersonReadConverter(), new PersonWriteConverter()); } } ``` -------------------------------- ### Write initial Liquibase change set Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/schema-support.adoc Creates a LiquibaseChangeSetWriter with a RelationalMappingContext that contains the Person entity, then writes the change set to a file system resource. ```java RelationalMappingContext context = … // The context contains the Person entity, ideally initialized through initialEntitySet LiquibaseChangeSetWriter writer = new LiquibaseChangeSetWriter(context); writer.writeChangeSet(new FileSystemResource(new File(…))); ``` -------------------------------- ### Run tests with all databases Source: https://github.com/spring-projects/spring-data-relational/blob/main/spring-data-jdbc/README.adoc Executes unit tests and all integration tests with all supported databases. ```bash mvn test -Pall-dbs ``` -------------------------------- ### Create person table SQL Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/getting-started.adoc SQL statement to create the person table with id, name, and age columns. ```sql CREATE TABLE person( id VARCHAR(255) PRIMARY KEY, name VARCHAR(255), age INT ); ``` -------------------------------- ### Docker image names for EULA acceptance Source: https://github.com/spring-projects/spring-data-relational/blob/main/spring-data-jdbc/README.adoc Names of Docker images that need to be accepted via a container-license-acceptance.txt file for Microsoft SQL Server and IBM DB2 testing. ```text mcr.microsoft.com/mssql/server:2022-latest ibmcom/db2:11.5.7.0a ``` -------------------------------- ### Registering a ConnectionFactory using Java Configuration Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/getting-started.adoc Use this configuration class to register an io.r2dbc.spi.ConnectionFactory bean. It extends AbstractR2dbcConfiguration, which also provides an ExceptionTranslator and registers DatabaseClient. The connectionFactory method must return a ConnectionFactory instance. ```java @Configuration public class ApplicationConfiguration extends AbstractR2dbcConfiguration { @Override @Bean public ConnectionFactory connectionFactory() { return … } } ``` -------------------------------- ### Supported keywords for query methods Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/query-methods.adoc Table of supported keywords, samples, and logical results for query method name derivation. ```text | And | findByLastnameAndFirstname | … WHERE lastname = :lastname AND firstname = :firstname | Or | findByLastnameOrFirstname | … WHERE lastname = :lastname OR firstname = :firstname | Is, Equals | findByFirstname, findByFirstnameIs, findByFirstnameEquals | … WHERE firstname = :firstname (or … WHERE firstname IS NULL if the argument is null) | Between | findByStartDateBetween | … WHERE startDate BETWEEN :startDate and :startDate1 | LessThan | findByAgeLessThan | … WHERE age < :age | LessThanEqual | findByAgeLessThanEqual | … WHERE age \<= :age | GreaterThan | findByAgeGreaterThan | … WHERE age > :age | GreaterThanEqual | findByAgeGreaterThanEqual | … WHERE age >= :age | After | findByStartDateAfter | … WHERE startDate > :startDate | Before | findByStartDateBefore | … WHERE startDate < :startDate | IsNull, Null | findByAge(Is)Null | … WHERE age IS NULL | IsNotNull, NotNull | findByAge(Is)NotNull | … WHERE age IS NOT NULL | Like | findByFirstnameLike | … WHERE firstname LIKE :firstname | NotLike | findByFirstnameNotLike | … WHERE firstname NOT LIKE :firstname | StartingWith | findByFirstnameStartingWith | … WHERE firstname LIKE :firstname (parameter bound with appended %) | EndingWith | findByFirstnameEndingWith | … WHERE firstname LIKE :firstname (parameter bound with prepended %) | Containing | findByFirstnameContaining | … WHERE firstname LIKE :firstname (parameter bound wrapped in %) | OrderBy | findByAgeOrderByLastnameDesc | … WHERE age = :age ORDER BY lastname DESC | Not | findByLastnameNot | … WHERE lastname <> :lastname (or … WHERE lastname IS NOT NULL if the argument is null) | In | findByAgeIn(Collection ages) | … WHERE age IN (:ages) | NotIn | findByAgeNotIn(Collection ages) | … WHERE age NOT IN (:ages) | True | findByActiveTrue() | … WHERE active = :active (with active being TRUE) | False | findByActiveFalse() | … WHERE active = :active (with active being FALSE) | IgnoreCase | findByFirstnameIgnoreCase | … where UPPER(firstname) = UPPER(:firstname) ``` -------------------------------- ### Java configuration for repositories Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/repositories.adoc Java configuration for enabling R2DBC repositories. Uses @EnableR2dbcRepositories and extends AbstractR2dbcConfiguration to provide a ConnectionFactory. If no base package is configured, the infrastructure scans the package of the annotated configuration class. ```java @Configuration @EnableR2dbcRepositories class ApplicationConfig extends AbstractR2dbcConfiguration { @Override public ConnectionFactory connectionFactory() { return … } } ``` -------------------------------- ### Configure R2DBC Entity Template with MySQL Dialect Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/repositories.adoc Returns an R2dbcEntityTemplate configured with a DatabaseClient and MySqlDialect.INSTANCE. This is used when you need a custom entity template for R2DBC repositories. ```java return new R2dbcEntityTemplate(databaseClient, MySqlDialect.INSTANCE); } } ``` -------------------------------- ### Run Integration Tests Ignoring Missing Licenses Source: https://github.com/spring-projects/spring-data-relational/blob/main/README.adoc Runs integration tests against all databases while ignoring tests that require explicit license acceptance by adding the 'ignore-missing-license' Maven profile. ```bash ./mvnw clean install -Pall-dbs,ignore-missing-license ``` -------------------------------- ### Multiple database configuration with @EnableR2dbcRepositories Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/repositories.adoc Configuration for working with multiple databases without using AbstractR2dbcConfiguration. It defines a ConnectionFactory bean and an R2dbcEntityOperations bean, and uses @EnableR2dbcRepositories with basePackages and entityOperationsRef to scan repositories for a specific database. ```java @Configuration @EnableR2dbcRepositories(basePackages = "com.acme.mysql", entityOperationsRef = "mysqlR2dbcEntityOperations") static class MySQLConfiguration { @Bean @Qualifier("mysql") public ConnectionFactory mysqlConnectionFactory() { return … } @Bean public R2dbcEntityOperations mysqlR2dbcEntityOperations(@Qualifier("mysql") ConnectionFactory connectionFactory) { DatabaseClient databaseClient = DatabaseClient.create(connectionFactory); ``` -------------------------------- ### Repository method declarations with derived, paginated, annotated, and named queries Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/aot.adoc Shows the repository method signatures used to generate AOT metadata. The methods include a derived query without arguments, a derived query with pagination, an annotated query, and a named query. ```java List findUserNoArgumentsBy(); <1> Page findPageOfUsersByLastnameStartingWith(String lastname, Pageable page); <2> @Query("select * from User u where username = ?1") User findAnnotatedQueryByEmailAddress(String username); <3> User findByEmailAddress(String emailAddress); <4> } ``` -------------------------------- ### Insert data with R2dbcEntityTemplate Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/entity-persistence.adoc Uses the insert() entry point to insert a Person object. The into(…) method sets the table based on mapping metadata. Provide a scalar Person object or a Publisher to run a stream of INSERT statements. ```java include::example$r2dbc/R2dbcEntityTemplateSnippets.java[tag=insert] ``` -------------------------------- ### PersonRepository with query methods Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/query-methods.adoc Defines a Spring Data JDBC repository interface with query methods demonstrating derived queries, pagination, slicing, single-entity retrieval, and @Query annotations. Includes methods for finding by firstname, ordering by lastname, returning Slice/Page, finding first by lastname, and using SpEL for dynamic parameters. ```java interface PersonRepository extends PagingAndSortingRepository { List findByFirstname(String firstname); <1> List findByFirstnameOrderByLastname(String firstname, Pageable pageable); <2> Slice findByLastname(String lastname, Pageable pageable); <3> Page findByLastname(String lastname, Pageable pageable); <4> Person findByFirstnameAndLastname(String firstname, String lastname); <5> Person findFirstByLastname(String lastname); <6> @Query("SELECT * FROM person WHERE lastname = :lastname") List findByLastname(String lastname); <7> @Query("SELECT * FROM person WHERE lastname = :lastname") Stream streamByLastname(String lastname); <8> @Query("SELECT * FROM person WHERE username = :#{ principal?.username }") Person findActiveUser(); <9> } ``` -------------------------------- ### Basic repository interface to persist Person entities Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/repositories.adoc Basic repository interface for persisting Person entities. Extends ReactiveCrudRepository to inherit reactive CRUD operations. ```java public interface PersonRepository extends ReactiveCrudRepository { // additional custom query methods go here } ``` -------------------------------- ### Add Spring Data R2DBC and H2 driver dependencies to pom.xml Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/getting-started.adoc Add these dependencies to the element of your pom.xml. The version placeholders {version} and x.y.z need to be replaced with actual versions. ```xml org.springframework.data spring-data-r2dbc {version} io.r2dbc r2dbc-h2 x.y.z ``` -------------------------------- ### Update data with R2dbcEntityTemplate Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/entity-persistence.adoc Uses the update() entry point to update rows. Specify the table with Update, set a different table name with inTable(…), and provide a Query for the WHERE clause. The Update object sets age to 42 and returns the number of affected rows. ```java Person modified = … include::example$r2dbc/R2dbcEntityTemplateSnippets.java[tag=update] ``` -------------------------------- ### Import MyBatisJdbcConfiguration in Java configuration Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/mybatis.adoc Use this configuration to plug MyBatis into Spring Data JDBC. It must be combined with @EnableJdbcRepositories and @Import(MyBatisJdbcConfiguration.class), and you need to declare a SqlSessionFactoryBean bean. MyBatisJdbcConfiguration expects a SqlSession bean to be available in the ApplicationContext. ```java @Configuration @EnableJdbcRepositories @Import(MyBatisJdbcConfiguration.class) class Application { @Bean SqlSessionFactoryBean sqlSessionFactoryBean() { // Configure MyBatis here } } ``` -------------------------------- ### Activating auditing with Java configuration Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/auditing.adoc Use this configuration class to enable JDBC auditing. It defines an AuditorAware bean that the auditing infrastructure will use to determine the current user. If multiple AuditorAware beans are present, set the auditorAwareRef attribute of @EnableJdbcAuditing to select one. ```java @Configuration @EnableJdbcAuditing class Config { @Bean AuditorAware auditorProvider() { return new AuditorAwareImpl(); } } ``` -------------------------------- ### Declaring and setting an AggregateReference Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/mapping.adoc Shows how to declare an AggregateReference field and assign it using AggregateReference.to(). The back reference is stored as a foreign key column. ```java class Person { @Id long id; AggregateReference bestFriend; } // ... Person p1, p2 = // some initialization p1.bestFriend = AggregateReference.to(p2.id); ``` -------------------------------- ### Delete data with R2dbcEntityTemplate Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/entity-persistence.adoc Uses the delete() entry point to delete rows. Specify the table with from(…) and optionally a Criteria for the WHERE clause. Returns the number of affected rows. ```java include::example$r2dbc/R2dbcEntityTemplateSnippets.java[tag=delete] ``` -------------------------------- ### Spring Data R2DBC Configuration Class Source: https://github.com/spring-projects/spring-data-relational/blob/main/README.adoc Configuration class enabling R2DBC repositories with a ConnectionFactory bean. The connection factory uses a placeholder URL that must be replaced with the actual driver, host, port, and database. ```java @Configuration @EnableR2dbcRepositories class ApplicationConfig extends AbstractR2dbcConfiguration { @Bean public ConnectionFactory connectionFactory() { return ConnectionFactories.get("r2dbc:://:/"); } } ``` -------------------------------- ### Enable R2DBC auditing with @EnableR2dbcAuditing and ReactiveAuditorAware bean Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/auditing.adoc Annotate a configuration class with @EnableR2dbcAuditing to activate auditing. Define a ReactiveAuditorAware bean to supply the current user; the infrastructure picks it up automatically. If multiple implementations exist, set the auditorAwareRef attribute of @EnableR2dbcAuditing to select one. ```java @Configuration @EnableR2dbcAuditing class Config { @Bean public ReactiveAuditorAware myAuditorProvider() { return new AuditorAwareImpl(); } } ``` -------------------------------- ### Sample Person entity Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/repositories.adoc Sample entity class used to demonstrate R2DBC repository usage. It defines a Person with an @Id field and two String properties, with getters and setters omitted for brevity. ```java public class Person { @Id private Long id; private String firstname; private String lastname; // … getters and setters omitted } ``` -------------------------------- ### Enable JDBC logging in application.properties Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/getting-started.adoc Sets the logging level for Spring's JDBC package to DEBUG in the application.properties file to inspect SQL statements. ```properties logging.level.org.springframework.jdbc=DEBUG ``` -------------------------------- ### Define a domain-specific listener using AbstractRelationalEventListener (Java) Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/events.adoc Defines a listener for Person aggregate roots only. It overrides onAfterLoad to log the loaded entity. Callback methods are only invoked for the specified domain type and its subtypes, so no casting is needed. ```java class PersonLoadListener extends AbstractRelationalEventListener { @Override protected void onAfterLoad(AfterLoadEvent personLoad) { LOG.info(personLoad.getEntity()); } } ``` -------------------------------- ### Enum Color and ColorConverter for Native Enum Mapping Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/mapping.adoc Shows the components needed to read and write Color enum values natively in databases like Postgres. The ColorConverter extends EnumWriteSupport to retain the actual enum value instead of using Enum.name(). You must also configure the enum type on the driver level. ```java enum Color { Grey, Blue } class ColorConverter extends EnumWriteSupport { } class Product { @Id long id; Color color; // … } ``` -------------------------------- ### Query with JdbcAggregateTemplate using query(where(...)) Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/entity-persistence.adoc Executes a programmatic query using JdbcAggregateTemplate's findOne method with a Query built from the static query and where methods. The Query defines columns, where clause, and limit/offset. Requires an entity instance with an identifier for some operations. ```java template.findOne(query(where("name").is("Gandalf")), Person.class); ``` -------------------------------- ### Maven Snapshot Repository Configuration Source: https://github.com/spring-projects/spring-data-relational/blob/main/README.adoc Configures the Spring snapshot repository and declares the spring-data-r2dbc dependency with a snapshot version. Use this to try the latest snapshots of the upcoming major version. ```xml org.springframework.data spring-data-r2dbc ${version}-SNAPSHOT spring-libs-snapshot Spring Snapshot Repository https://repo.spring.io/snapshot ``` -------------------------------- ### Use @Embedded.Nullable shortcut for @Embedded(onEmpty = USE_NULL) Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/partials/mapping.adoc Shows the @Embedded.Nullable shortcut for @Embedded(onEmpty = USE_NULL). The annotation also sets JSR-305 @javax.annotation.Nonnull accordingly. ```java class MyEntity { @Id Integer id; @Embedded.Nullable <1> EmbeddedEntity embeddedEntity; } ``` -------------------------------- ### Spring Data JDBC repositories using Java configuration Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/getting-started.adoc Java configuration class that enables Spring Data JDBC repositories using @EnableJdbcRepositories and extends AbstractJdbcConfiguration. It defines beans for DataSource, NamedParameterJdbcOperations, and TransactionManager. ```java @Configuration @EnableJdbcRepositories // <1> class ApplicationConfig extends AbstractJdbcConfiguration { // <2> @Bean DataSource dataSource() { // <3> EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); return builder.setType(EmbeddedDatabaseType.HSQL).build(); } @Bean NamedParameterJdbcOperations namedParameterJdbcOperations(DataSource dataSource) { // <4> return new NamedParameterJdbcTemplate(dataSource); } @Bean TransactionManager transactionManager(DataSource dataSource) { // <5> return new DataSourceTransactionManager(dataSource); } } ``` -------------------------------- ### Upsert data with R2dbcEntityOperations Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/entity-persistence.adoc Uses the upsert(instance) operation to persist an entity in a single round-trip. Requires an identifier value and database dialect support (PostgreSQL, H2, MySQL, MariaDB, SQL Server, Oracle, HSQLDB). Does not support optimistic locking. ```java Person modified = … include::example$r2dbc/R2dbcEntityTemplateSnippets.java[tag=upsert] ``` -------------------------------- ### Declare a query method by using @Query Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/query-methods.adoc Declares a query method with @Query and named parameter binding. Note that String-based queries do not support pagination or Sort, PageRequest, and Limit parameters. ```java interface UserRepository extends ReactiveCrudRepository { @Query("SELECT first_name, last_name FROM user WHERE email_address = :email") Flux findByEmailAddress(@Param("email") String email); } ``` -------------------------------- ### Using a facade to define transactions for multiple repository calls Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/transactions.adoc A service implementation that defines a transactional boundary for multiple repository calls. The @Transactional annotation on the method makes the whole operation run in a transaction, participating in an existing one or creating a new one. Requires @EnableTransactionManagement or and component scanning. ```java @Service public class UserManagementImpl implements UserManagement { private final UserRepository userRepository; private final RoleRepository roleRepository; UserManagementImpl(UserRepository userRepository, RoleRepository roleRepository) { this.userRepository = userRepository; this.roleRepository = roleRepository; } @Transactional public void addRoleToAllUsers(String roleName) { Role role = roleRepository.findByName(roleName); for (User user : userRepository.findAll()) { user.addRole(role); userRepository.save(user); } } } ``` -------------------------------- ### Custom transaction configuration for CRUD Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/transactions.adoc Redeclare a repository method to override its transaction configuration. Here, findAll() is given a timeout of 10 seconds and the readOnly flag is not set. ```java interface UserRepository extends CrudRepository { @Override @Transactional(timeout = 10) List findAll(); // Further query method declarations } ``` -------------------------------- ### Configure drop filters for differential schema updates Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/schema-support.adoc Configures filters to control which tables and columns can be dropped in differential mode. By default, no tables or columns are dropped unless these filters are set. ```java writer.setDropTableFilter(tableName -> …); writer.setDropColumnFilter((tableName, columnName) -> …); ``` -------------------------------- ### Derived Delete Query with ReactivePersonRepository Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/query-methods.adoc Declares derived delete queries using delete…By keywords. Return types Mono, Mono, and Mono report affected rows, success without a value, or whether at least one row was removed, respectively. ```java interface ReactivePersonRepository extends ReactiveSortingRepository { Mono deleteByLastname(String lastname); <1> Mono deletePersonByLastname(String lastname); <2> Mono deletePersonByLastname(String lastname); <3> } ``` -------------------------------- ### Add Spring Data JDBC dependency to pom.xml Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/getting-started.adoc Adds the spring-data-jdbc dependency to the Maven pom.xml file. The version is specified by the {version} attribute placeholder. ```xml org.springframework.data spring-data-jdbc {version} ``` -------------------------------- ### Add Spring Milestone repository to pom.xml Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/getting-started.adoc Adds the Spring Milestone Maven repository to the pom.xml file. This repository is required to resolve milestone versions of Spring Data JDBC. ```xml spring-milestone Spring Maven MILESTONE Repository https://repo.spring.io/milestone ``` -------------------------------- ### Registering Converters with JdbcConverter Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/mapping.adoc Override userConverters() in AbstractJdbcConfiguration to register custom converters. In older versions, overriding jdbcCustomConversions() was recommended but is no longer necessary. ```java class MyJdbcConfiguration extends AbstractJdbcConfiguration { // … @Override protected List userConverters() { return Arrays.asList(new BooleanToStringConverter(), new StringToBooleanConverter()); } } ``` -------------------------------- ### Use a SpEL in a query Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/query-methods.adoc SpEL expressions prefixed with ':' are replaced with bind variables. The variable is bound to the result of the SpEL expression. ```java @Query("SELECT * FROM person WHERE id = :#{#person.id}") Person findWithSpEL(PersonRef person); ``` -------------------------------- ### Set Spring version in pom.xml Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/getting-started.adoc Sets the Spring version property in the pom.xml file. The value is specified by the {springVersion} attribute placeholder. ```xml {springVersion} ``` -------------------------------- ### Maven Dependency for Spring Data R2DBC Source: https://github.com/spring-projects/spring-data-relational/blob/main/README.adoc Adds the spring-data-r2dbc dependency to a Maven project. The version is specified with a placeholder that should be replaced with the actual version. ```xml org.springframework.data spring-data-r2dbc ${version} ``` -------------------------------- ### Register QueryMappingConfiguration bean Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/query-methods.adoc Registers a QueryMappingConfiguration bean to provide custom RowMapper instances for specific return types. The configuration maps Person and Address classes to their respective RowMappers. ```java @Bean QueryMappingConfiguration rowMappers() { return new DefaultQueryMappingConfiguration() .register(Person.class, new PersonRowMapper()) .register(Address.class, new AddressRowMapper()); } ``` -------------------------------- ### Set logging level to DEBUG in application.properties Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/getting-started.adoc Edit the application.properties file to set the logging level for Spring Data R2DBC to DEBUG. ```properties logging.level.org.springframework.r2dbc=DEBUG ``` -------------------------------- ### Maven Dependency for spring-data-jdbc Source: https://github.com/spring-projects/spring-data-relational/blob/main/README.adoc Add the Maven dependency for spring-data-jdbc. Use the version ${version} for releases. ```xml org.springframework.data spring-data-jdbc ${version} ``` -------------------------------- ### SpEL Expression for Predicate Value (include directive) Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/query-methods.adoc Shows a query using a SpEL expression to provide a predicate value. The actual code is included from an external file via an include directive and is not displayed on this page. ```java include::example$r2dbc/PersonRepository.java[tags=spel] ``` -------------------------------- ### SpEL Expression in Query Middle (include directive) Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/query-methods.adoc Shows a query using a SpEL expression in the middle of the query string. The actual code is included from an external file via an include directive and is not displayed on this page. ```java include::example$r2dbc/PersonRepository.java[tags=spel2] ``` -------------------------------- ### Generated AOT JSON metadata for UserRepository Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/aot.adoc The JSON metadata generated for the repository methods shown above. It includes query descriptors for derived, annotated, and named queries, as well as a fragment for the count method. ```json { "name": "com.acme.UserRepository", "module": "JDBC", "type": "IMPERATIVE", "methods": [ { "name": "findUserNoArgumentsBy", "signature": "public abstract java.util.List com.acme.UserRepository.findUserNoArgumentsBy()", "query": { "query": "SELECT * FROM User" } }, { "name": "findPageOfUsersByLastnameStartingWith", "signature": "public abstract org.springframework.data.domain.Page com.acme.UserRepository.findPageOfUsersByLastnameStartingWith(java.lang.String,org.springframework.data.domain.Pageable)", "query": { "query": "SELECT * FROM User u WHERE lastname LIKE :lastname", "count-query": "SELECT COUNT(*) FROM User WHERE lastname LIKE :lastname" } }, { "name": "findAnnotatedQueryByEmailAddress", "signature": "public abstract com.acme.User com.acme.UserRepository.findAnnotatedQueryByEmailAddress(java.lang.String)", "query": { "query": "select * from User where emailAddress = ?1" } }, { "name": "findByEmailAddress", "signature": "public abstract com.acme.User com.acme.UserRepository.findByEmailAddress(java.lang.String)", "query": { "name": "User.findByEmailAddress", "query": "SELECT * FROM User WHERE emailAddress = ?1" } }, { "name": "count", "signature": "public abstract long org.springframework.data.repository.CrudRepository.count()", "fragment": { "fragment": "org.springframework.data.jdbc.repository.support.SimpleJdbcRepository" } } ] } ``` -------------------------------- ### BooleanToStringConverter implementation Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/mapping.adoc Implements a Converter that converts Boolean to String, returning "T" for true and "F" for false. Uses @WritingConverter annotation. ```java import org.springframework.core.convert.converter.Converter; @WritingConverter public class BooleanToStringConverter implements Converter { @Override public String convert(Boolean source) { return source != null && source ? "T" : "F"; } } ``` -------------------------------- ### Declare a query method by using @Query Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/query-methods.adoc Use @Query to define a custom query. The query must match the format expected by the RowMapper, providing columns for all constructor properties. Properties set via setter, wither, or field access are optional. The query is used for populating the aggregate root, embedded entities, and one-to-one relationships. ```java interface UserRepository extends CrudRepository { @Query("SELECT first_name, last_name FROM user WHERE email_address = :email") User findByEmailAddress(@Param("email") String email); } ``` -------------------------------- ### PersonReadConverter implementing Converter Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/mapping.adoc Register custom converters with R2dbcConverter to selectively handle conversion. This @ReadingConverter converts from R2DBC's Row to a Person POJO. Requires asymmetric types for top-level entity conversion. ```java @ReadingConverter public class PersonReadConverter implements Converter { ``` -------------------------------- ### Reading Converter: String to Boolean Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/mapping.adoc Converts a String from the database to a Boolean property. Annotate with @ReadingConverter to indicate direction. Returns TRUE if source equals 'T' (case-insensitive), otherwise FALSE. ```java @ReadingConverter public class StringToBooleanConverter implements Converter { @Override public Boolean convert(String source) { return source != null && source.equalsIgnoreCase("T") ? Boolean.TRUE : Boolean.FALSE; } } ``` -------------------------------- ### PersonWriteConverter: Convert Person to OutboundRow Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/r2dbc/mapping.adoc Converts a Person entity to an OutboundRow for writing to the database. Uses @WritingConverter and Parameter.from() to wrap values. This converter is used when writing Person instances. ```java @WritingConverter public class PersonWriteConverter implements Converter { public OutboundRow convert(Person source) { OutboundRow row = new OutboundRow(); row.put("id", Parameter.from(source.getId())); row.put("name", Parameter.from(source.getFirstName())); row.put("age", Parameter.from(source.getAge())); return row; } } ``` -------------------------------- ### Customize key column with @MappedCollection keyColumn Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/partials/mapping.adoc When using List or Map with @MappedCollection, you must have an additional column for the position or key value. The keyColumn element customizes that column name, as shown with CUSTOM_KEY_COLUMN_NAME. ```java class MyEntity { @Id Integer id; @MappedCollection(idColumn = "CUSTOM_COLUMN_NAME", keyColumn = "CUSTOM_KEY_COLUMN_NAME") List name; } class MySubEntity { String name; } ``` -------------------------------- ### Select for next sequence value in PostgreSQL Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/partials/sequences.adoc Spring Data issues this SELECT statement to fetch the next value from the sequence before inserting the entity. The query uses the sequence name and schema from the @Sequence annotation. ```sql SELECT nextval('public.my_seq'); ``` -------------------------------- ### Person domain entity Source: https://github.com/spring-projects/spring-data-relational/blob/main/src/main/antora/modules/ROOT/pages/jdbc/schema-support.adoc Defines a domain entity annotated with @Table and @Id. The entity is used by the LiquibaseChangeSetWriter to generate the initial database change set. ```java @Table class Person { @Id long id; String firstName; String lastName; LocalDate birthday; boolean active; } ```