#2 - Polishing.

This commit is contained in:
Mark Paluch
2018-10-17 11:04:34 +02:00
parent ce0a707500
commit 12dc98bcbd
28 changed files with 254 additions and 753 deletions

View File

@@ -1,88 +1,196 @@
image:https://spring.io/badges/spring-data-jdbc/ga.svg["Spring Data JDBC", link="https://spring.io/projects/spring-data-jdbc#learn"]
image:https://spring.io/badges/spring-data-jdbc/snapshot.svg["Spring Data JDBC", link="https://spring.io/projects/spring-data-jdbc#learn"]
= Spring Data R2DBC
= Spring Data JDBC
The primary goal of the http://projects.spring.io/spring-data[Spring Data] project is to make it easier to build Spring-powered applications that use data access technologies. *Spring Data R2DBC* offers the popular Repository abstraction based on https://r2dbc.io[R2DBC].
The primary goal of the http://projects.spring.io/spring-data[Spring Data] project is to make it easier to build Spring-powered applications that use data access technologies. *Spring Data JDBC* offers the popular Repository abstraction based on JDBC.
R2DBC is the abbreviation for https://github.com/r2dbc/[Reactive Relational Database Connectivity], an incubator to integrate relational databases using a reactive driver.
It aims at being conceptually easy.
In order to achieve this it does NOT offer caching, lazy loading, write behind or many other features of JPA.
This makes Spring Data JDBC a simple, limited, opinionated ORM.
The state of R2DBC is incubating to evaluate how an reactive integration could look like. To get started, you need a R2DBC driver first.
== Features
== This is NOT an ORM
* Implementation of CRUD methods for Aggregates.
* `@Query` annotation
* Support for transparent auditing (created, last changed)
* Events for persistence events
* Possibility to integrate custom repository code
* JavaConfig based repository configuration by introducing `EnableJdbcRepository`
* Integration with MyBatis
Spring Data R2DBC does not try to be an ORM.
Instead it is more of a construction kit for your personal reactive relational data access component that you can define the way you like or need it.
== Getting Help
== Maven Coordinates
If you are new to Spring Data JDBC read the following two articles https://spring.io/blog/2018/09/17/introducing-spring-data-jdbc["Introducing Spring Data JDBC"] and https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates["Spring Data JDBC, References, and Aggregates"]
There are also examples in the https://github.com/spring-projects/spring-data-examples/tree/master/jdbc[Spring Data Examples] project.
A very good source of information is the source code in this repository.
Especially the integration tests (if you are reading this on github, type `t` and then `IntegrationTests.java`)
We are keeping an eye on the (soon to be created) https://stackoverflow.com/questions/tagged/spring-data-jdbc[spring-data-jdbc tag on stackoverflow].
If you think you found a bug, or have a feature request please https://jira.spring.io/browse/DATAJDBC/?selectedTab=com.atlassian.jira.jira-projects-plugin:summary-panel[create a ticket in our issue tracker].
== Execute Tests
=== Fast running tests
Fast running tests can be executed with a simple
[source]
[source,xml]
----
mvn test
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-r2dbc</artifactId>
<version>1.0.0.BUILD-SNAPSHOT</version>
</dependency>
----
This will execute unit tests and integration tests using an in-memory database.
=== Running tests with a real database
== DatabaseClient
In order to run the integration tests against a specific database you need to have a local Docker installation available, and then execute.
All functionality is encapsulated in `DatabaseClient` which is the entry point for applications that wish to integrate with relational databases using reactive drivers:
[source]
[source,java]
----
mvn test -Dspring.profiles.active=<databasetype>
PostgresqlConnectionFactory connectionFactory = new PostgresqlConnectionFactory(PostgresqlConnectionConfiguration.builder()
.host(…)
.database(…)
.username(…)
.password(…).build());
DatabaseClient databaseClient = DatabaseClient.create(connectionFactory);
----
This will also execute the unit tests.
The client API provides covers the following features:
Currently the following _databasetypes_ are available:
* Execution of generic SQL and consumption of update count/row results.
* Generic `SELECT` with paging and ordering.
* `SELECT` of mapped objects with paging and ordering.
* Generic `INSERT` with parameter binding.
* `INSERT` of mapped objects.
* Parameter binding using the native syntax.
* Result consumption: Update count, unmapped (`Map<String, Object>`), mapped to entities, extraction function.
* Reactive repositories using `@Query` annotated methods.
* Transaction Management.
* hsql (default, does not require a running database)
* mysql
* postgres
* mariadb
=== Examples executing generic SQL statements
=== Run tests with all databases
[source]
[source,java]
----
mvn test -Pall-dbs
Mono<Integer> count = databaseClient.execute()
.sql("INSERT INTO legoset (id, name, manual) VALUES($1, $2, $3)")
.bind("$1", 42055)
.bind("$2", "Description")
.bindNull("$3", Integer.class)
.fetch()
.rowsUpdated();
Flux<Map<String, Object>> rows = databaseClient.execute()
.sql("SELECT id, name, manual FROM legoset")
.fetch().all();
Flux<Long> result = db.execute()
.sql("SELECT txid_current();")
.exchange()
.flatMapMany(it -> it.extract((r, md) -> r.get(0, Long.class)).all());
----
This will execute the unit tests, and all the integration tests with all the databases we currently support for testing. Running the integration-tests depends on Docker.
=== Examples selecting data
== Contributing to Spring Data JDBC
[source,java]
----
Flux<Map<String, Object>> rows = databaseClient.select()
.from("legoset")
.orderBy(Sort.by(desc("id")))
.fetch()
.all();
Flux<LegoSet> rows = databaseClient.select()
.from("legoset")
.orderBy(Sort.by(desc("id")))
.as(LegoSet.class)
.fetch()
.all();
----
=== Examples inserting data
[source,java]
----
Flux<Integer> ids = databaseClient.insert()
.into("legoset")
.value("id", 42055)
.value("name", "Description")
.nullValue("manual", Integer.class)
.exchange() //
.flatMapMany(it -> it.extract((r, m) -> r.get("id", Integer.class)).all())
Flux<Integer> ids = databaseClient.insert()
.into(LegoSet.class)
.using(legoSet)
.exchange()
.flatMapMany(it -> it.extract((r, m) -> r.get("id", Integer.class)).all())
----
=== Examples using reactive repositories
[source,java]
----
interface LegoSetRepository extends ReactiveCrudRepository<LegoSet, Integer> {
@Query("SELECT * FROM legoset WHERE name like $1")
Flux<LegoSet> findByNameContains(String name);
@Query("SELECT * FROM legoset WHERE manual = $1")
Mono<LegoSet> findByManual(int manual);
}
----
=== Examples using transaction control
All examples above run with auto-committed transactions. To get group multiple statements within the same transaction or
control the transaction yourself, you need to use `TransactionalDatabaseClient`:
[source,java]
----
TransactionalDatabaseClient databaseClient = TransactionalDatabaseClient.create(connectionFactory);
----
`TransactionalDatabaseClient` allows multiple flavors of transaction management:
* Participate in ongoing transactions and fall-back to auto-commit mode if there's no active transaction (default).
* Group multiple statements in a managed transaction using `TransactionalDatabaseClient.inTransaction(…)`.
* Application-controlled transaction management using `TransactionalDatabaseClient.beginTransaction()`/`commitTransaction()`/`rollbackTransaction()`.
Participating in ongoing transactions does not require changes to your application code. Instead, a managed transaction must be hosted by your application container. Transaction control needs to happen there, as well.
**Statement grouping**
[source,java]
----
Flux<Integer> rowsUpdated = databaseClient.inTransaction(db -> {
return db.execute().sql("INSERT INTO legoset (id, name, manual) VALUES($1, $2, $3)") //
.bind(0, 42055) //
.bind(1, "Description") //
.bindNull("$3", Integer.class) //
.fetch()
.rowsUpdated();
});
----
**Application-controlled transaction management**
[source,java]
----
Flux<Long> txId = databaseClient.execute().sql("SELECT txid_current();").exchange()
.flatMapMany(it -> it.extract((r, md) -> r.get(0, Long.class)).all());
Mono<Void> then = databaseClient.enableTransactionSynchronization(databaseClient.beginTransaction() //
.thenMany(txId)) //
.then(databaseClient.rollbackTransaction()));
----
NOTE: Application-controlled transactions must be enabled with `enableTransactionSynchronization(…)`.
== Building from Source
You don't need to build from source to use Spring Data R2DBC (binaries in https://repo.spring.io[repo.spring.io]), but if you want to try out the latest and greatest, Spring Data R2DBC can be easily built with the https://github.com/takari/maven-wrapper[maven wrapper]. You also need JDK 1.8.
[indent=0]
----
$ ./mvnw clean install
----
If you want to build with the regular `mvn` command, you will need https://maven.apache.org/run-maven/index.html[Maven v3.5.0 or above].
_Also see link:CONTRIBUTING.adoc[CONTRIBUTING.adoc] if you wish to submit pull requests, and in particular please fill out the https://cla.pivotal.io/[Contributor's Agreement] before your first change._
== Contributing to Spring Data R2DBC
Here are some ways for you to get involved in the community:
* Get involved with the Spring community by helping out on http://stackoverflow.com/questions/tagged/spring-data-jdbc[stackoverflow] by responding to questions and joining the debate.
* Create https://jira.spring.io/browse/DATAJDBC[JIRA] tickets for bugs and new features and comment and vote on the ones that you are interested in.
* Get involved with the Spring community by helping out on http://stackoverflow.com/questions/tagged/spring-data-r2dbc[Stackoverflow] by responding to questions and joining the debate.
* Create https://github.com/spring-data/spring-data-r2dbc[GitHub] tickets for bugs and new features and comment and vote on the ones that you are interested in.
* Github is for social coding: if you want to write code, we encourage contributions through pull requests from http://help.github.com/forking/[forks of this repository]. If you want to contribute code this way, please reference a JIRA ticket as well, covering the specific issue you are addressing.
* Watch for upcoming articles on Spring by http://spring.io/blog[subscribing] to spring.io.
Before we accept a non-trivial patch or pull request we will need you to https://cla.pivotal.io/sign/spring[sign the Contributor License Agreement]. Signing the contributors agreement does not grant anyone commit rights to the main repository, but it does mean that we can accept your contributions, and you will get an author credit if we do. If you forget to do so, you'll be reminded when you submit a pull request. Active contributors might be asked to join the core team, and given the ability to merge pull requests.
== License
link:src/main/resources/license.txt[The license und which Spring Data JDBC is published can be found here].

90
pom.xml
View File

@@ -5,12 +5,12 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jdbc</artifactId>
<version>1.1.0.r2dbc-SNAPSHOT</version>
<artifactId>spring-data-r2dbc</artifactId>
<version>1.0.0.BUILD-SNAPSHOT</version>
<name>Spring Data JDBC</name>
<description>Spring Data module for JDBC repositories.</description>
<url>http://projects.spring.io/spring-data-jdbc</url>
<name>Spring Data R2DBC</name>
<description>Spring Data module for R2DBC.</description>
<url>http://projects.spring.io/spring-data-r2dbc</url>
<parent>
<groupId>org.springframework.data.build</groupId>
@@ -20,33 +20,29 @@
<properties>
<dist.key>DATAJDBC</dist.key>
<dist.key>DATAR2DBC</dist.key>
<springdata.commons>2.2.0.BUILD-SNAPSHOT</springdata.commons>
<java-module-name>spring.data.jdbc</java-module-name>
<springdata.relational>1.1.0.BUILD-SNAPSHOT</springdata.relational>
<java-module-name>spring.data.r2dbc</java-module-name>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
<assertj-core.version>3.6.2</assertj-core.version>
<degraph-check.version>0.1.4</degraph-check.version>
<hsqldb.version>2.2.8</hsqldb.version>
<mybatis.version>3.4.6</mybatis.version>
<mybatis-spring.version>1.3.2</mybatis-spring.version>
<mysql-connector-java.version>5.1.41</mysql-connector-java.version>
<postgresql.version>42.0.0</postgresql.version>
<mariadb-java-client.version>2.2.3</mariadb-java-client.version>
<r2dbc-spi.version>1.0.0.M5</r2dbc-spi.version>
<r2dbc-postgresql.version>1.0.0.M5</r2dbc-postgresql.version>
<testcontainers.version>1.7.3</testcontainers.version>
</properties>
<inceptionYear>2017</inceptionYear>
<inceptionYear>2018</inceptionYear>
<developers>
<developer>
<id>schauder</id>
<name>Jens Schauder</name>
<email>jschauder(at)pivotal.io</email>
<id>mpaluch</id>
<name>Mark Paluch</name>
<email>mpaluch(at)pivotal.io</email>
<organization>Pivotal Software, Inc.</organization>
<organizationUrl>https://pivotal.io</organizationUrl>
<roles>
@@ -55,15 +51,15 @@
<timezone>+1</timezone>
</developer>
<developer>
<id>gregturn</id>
<name>Greg L. Turnquist</name>
<email>gturnquist(at)pivotal.io</email>
<id>ogierke</id>
<name>Oliver Gierke</name>
<email>ogierke(at)pivotal.io</email>
<organization>Pivotal Software, Inc.</organization>
<organizationUrl>https://pivotal.io</organizationUrl>
<roles>
<role>Project Contributor</role>
<role>Project Lead</role>
</roles>
<timezone>-6</timezone>
<timezone>+1</timezone>
</developer>
</developers>
@@ -177,6 +173,12 @@
<version>${springdata.commons}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>spring-data-relational</artifactId>
<version>${springdata.relational}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
@@ -206,40 +208,17 @@
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-spi</artifactId>
<version>${r2dbc-spi.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<version>${assertj}</version>
<scope>test</scope>
</dependency>
@@ -249,13 +228,6 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
@@ -263,13 +235,6 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>${mariadb-java-client.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-postgresql</artifactId>
@@ -304,13 +269,6 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mariadb</artifactId>
<version>${testcontainers.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@@ -1,68 +0,0 @@
/*
* Copyright 2017-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.jdbc.repository.config;
import java.util.Locale;
import org.springframework.data.jdbc.repository.support.JdbcRepositoryFactoryBean;
import org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport;
import org.springframework.data.repository.core.RepositoryMetadata;
/**
* {@link org.springframework.data.repository.config.RepositoryConfigurationExtension} extending the repository
* registration process by registering JDBC repositories.
*
* @author Jens Schauder
* @author Mark Paluch
*/
public class JdbcRepositoryConfigExtension extends RepositoryConfigurationExtensionSupport {
/*
* (non-Javadoc)
* @see org.springframework.data.repository.config.RepositoryConfigurationExtension#getModuleName()
*/
@Override
public String getModuleName() {
return "JDBC";
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport#getRepositoryFactoryBeanClassName()
*/
@Override
public String getRepositoryFactoryBeanClassName() {
return JdbcRepositoryFactoryBean.class.getName();
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport#getModulePrefix()
*/
@Override
protected String getModulePrefix() {
return getModuleName().toLowerCase(Locale.US);
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport#useRepositoryConfiguration(org.springframework.data.repository.core.RepositoryMetadata)
*/
@Override
protected boolean useRepositoryConfiguration(RepositoryMetadata metadata) {
return !metadata.isReactiveRepository();
}
}

View File

@@ -315,7 +315,6 @@ public interface DatabaseClient {
*/
S project(String... selectedFields);
/**
* Configure {@link Sort}.
*

View File

@@ -48,28 +48,27 @@ class DefaultSqlResult<T> implements SqlResult<T> {
this.resultFunction = resultFunction;
this.updatedRowsFunction = updatedRowsFunction;
this.fetchSpec = new DefaultFetchSpec<>(connectionAccessor, sql,
new SqlFunction<Connection, Flux<T>>() {
@Override
public Flux<T> apply(Connection connection) {
return resultFunction.apply(connection).flatMap(result -> result.map(mappingFunction));
}
this.fetchSpec = new DefaultFetchSpec<>(connectionAccessor, sql, new SqlFunction<Connection, Flux<T>>() {
@Override
public Flux<T> apply(Connection connection) {
return resultFunction.apply(connection).flatMap(result -> result.map(mappingFunction));
}
@Override
public String getSql() {
return sql;
}
}, new SqlFunction<Connection, Mono<Integer>>() {
@Override
public Mono<Integer> apply(Connection connection) {
return updatedRowsFunction.apply(connection);
}
@Override
public String getSql() {
return sql;
}
}, new SqlFunction<Connection, Mono<Integer>>() {
@Override
public Mono<Integer> apply(Connection connection) {
return updatedRowsFunction.apply(connection);
}
@Override
public String getSql() {
return sql;
}
});
@Override
public String getSql() {
return sql;
}
});
}
/* (non-Javadoc)

View File

@@ -155,8 +155,7 @@ public class EntityRowMapper<T> implements BiFunction<Row, RowMetadata, T> {
String column = prefix + entity.getRequiredPersistentProperty(parameter.getName()).getColumnName();
try {
return conversionService.convert(resultSet.get(column),
parameter.getType().getType());
return conversionService.convert(resultSet.get(column), parameter.getType().getType());
} catch (Exception o_O) {
throw new MappingException(String.format("Couldn't read column %s from Row.", column), o_O);
}

View File

@@ -109,4 +109,3 @@ public class MappingR2dbcConverter {
return relationalConverter.getMappingContext();
}
}

View File

@@ -13,25 +13,29 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.relational.repository.query;
package org.springframework.data.r2dbc.repository.query;
import org.springframework.data.repository.query.ParameterAccessor;
import org.springframework.data.repository.query.Parameters;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.data.annotation.QueryAnnotation;
/**
* JDBC-specific {@link ParameterAccessor}.
*
* Annotation to provide SQL statements that will get used for executing the method.
*
* @author Mark Paluch
*/
public interface RelationalParameterAccessor extends ParameterAccessor {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@QueryAnnotation
@Documented
public @interface Query {
/**
* Returns the raw parameter values of the underlying query method.
* The SQL statement to execute when the annotated method gets invoked.
*/
Object[] getValues();
/**
* @return the bindable parameters.
*/
Parameters<?, ?> getBindableParameters();
String value();
}

View File

@@ -26,7 +26,6 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.projection.ProjectionFactory;
import org.springframework.data.relational.core.mapping.RelationalPersistentEntity;

View File

@@ -15,7 +15,6 @@
*/
package org.springframework.data.r2dbc.repository.query;
import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.r2dbc.function.DatabaseClient;
import org.springframework.data.r2dbc.function.DatabaseClient.BindSpec;
import org.springframework.data.r2dbc.function.convert.MappingR2dbcConverter;

View File

@@ -1,108 +0,0 @@
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.relational.repository.query;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.EntityInstantiator;
import org.springframework.data.convert.EntityInstantiators;
import org.springframework.data.mapping.PersistentEntity;
import org.springframework.data.mapping.PersistentProperty;
import org.springframework.data.mapping.PersistentPropertyAccessor;
import org.springframework.data.mapping.PreferredConstructor;
import org.springframework.data.mapping.PreferredConstructor.Parameter;
import org.springframework.data.mapping.SimplePropertyHandler;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mapping.model.ParameterValueProvider;
import org.springframework.data.relational.core.mapping.RelationalPersistentEntity;
import org.springframework.data.relational.core.mapping.RelationalPersistentProperty;
import org.springframework.util.Assert;
/**
* {@link Converter} to instantiate DTOs from fully equipped domain objects.
*
* @author Mark Paluch
*/
public class DtoInstantiatingConverter implements Converter<Object, Object> {
private final Class<?> targetType;
private final MappingContext<? extends PersistentEntity<?, ?>, ? extends PersistentProperty<?>> context;
private final EntityInstantiator instantiator;
/**
* Creates a new {@link Converter} to instantiate DTOs.
*
* @param dtoType must not be {@literal null}.
* @param context must not be {@literal null}.
* @param instantiators must not be {@literal null}.
*/
public DtoInstantiatingConverter(Class<?> dtoType,
MappingContext<? extends RelationalPersistentEntity<?>, ? extends RelationalPersistentProperty> context,
EntityInstantiators instantiator) {
Assert.notNull(dtoType, "DTO type must not be null!");
Assert.notNull(context, "MappingContext must not be null!");
Assert.notNull(instantiator, "EntityInstantiators must not be null!");
this.targetType = dtoType;
this.context = context;
this.instantiator = instantiator.getInstantiatorFor(context.getRequiredPersistentEntity(dtoType));
}
/*
* (non-Javadoc)
* @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object)
*/
@Override
public Object convert(Object source) {
if (targetType.isInterface()) {
return source;
}
final PersistentEntity<?, ?> sourceEntity = context.getRequiredPersistentEntity(source.getClass());
final PersistentPropertyAccessor sourceAccessor = sourceEntity.getPropertyAccessor(source);
final PersistentEntity<?, ?> targetEntity = context.getRequiredPersistentEntity(targetType);
final PreferredConstructor<?, ? extends PersistentProperty<?>> constructor = targetEntity
.getPersistenceConstructor();
@SuppressWarnings({ "rawtypes", "unchecked" })
Object dto = instantiator.createInstance(targetEntity, new ParameterValueProvider() {
@Override
public Object getParameterValue(Parameter parameter) {
return sourceAccessor.getProperty(sourceEntity.getPersistentProperty(parameter.getName()));
}
});
final PersistentPropertyAccessor dtoAccessor = targetEntity.getPropertyAccessor(dto);
targetEntity.doWithProperties(new SimplePropertyHandler() {
@Override
public void doWithPersistentProperty(PersistentProperty<?> property) {
if (constructor.isConstructorParameter(property)) {
return;
}
dtoAccessor.setProperty(property,
sourceAccessor.getProperty(sourceEntity.getPersistentProperty(property.getName())));
}
});
return dto;
}
}

View File

@@ -1,33 +0,0 @@
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.relational.repository.query;
import org.springframework.data.repository.core.EntityInformation;
/**
* Relational database-specific {@link EntityInformation}.
*
* @author Mark Paluch
*/
public interface RelationalEntityInformation<T, ID> extends EntityInformation<T, ID> {
/**
* Returns the name of the table the entity shall be persisted to.
*
* @return
*/
String getTableName();
}

View File

@@ -1,41 +0,0 @@
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.relational.repository.query;
import org.springframework.data.relational.core.mapping.RelationalPersistentEntity;
import org.springframework.data.repository.core.EntityMetadata;
/**
* Extension of {@link EntityMetadata} to additionally expose the collection name an entity shall be persisted to.
*
* @author Mark Paluch
*/
public interface RelationalEntityMetadata<T> extends EntityMetadata<T> {
/**
* Returns the name of the table the entity shall be persisted to.
*
* @return
*/
String getTableName();
/**
* Returns the {@link RelationalPersistentEntity} that supposed to determine the table to be queried.
*
* @return
*/
RelationalPersistentEntity<?> getTableEntity();
}

View File

@@ -1,80 +0,0 @@
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.relational.repository.query;
import java.lang.reflect.Method;
import java.util.List;
import org.springframework.core.MethodParameter;
import org.springframework.data.relational.repository.query.RelationalParameters.RelationalParameter;
import org.springframework.data.repository.query.Parameter;
import org.springframework.data.repository.query.Parameters;
/**
* Custom extension of {@link Parameters}.
*
* @author Mark Paluch
*/
public class RelationalParameters extends Parameters<RelationalParameters, RelationalParameter> {
/**
* Creates a new {@link RelationalParameters} instance from the given {@link Method}.
*
* @param method must not be {@literal null}.
*/
public RelationalParameters(Method method) {
super(method);
}
private RelationalParameters(List<RelationalParameter> parameters) {
super(parameters);
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.Parameters#createParameter(org.springframework.core.MethodParameter)
*/
@Override
protected RelationalParameter createParameter(MethodParameter parameter) {
return new RelationalParameter(parameter);
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.Parameters#createFrom(java.util.List)
*/
@Override
protected RelationalParameters createFrom(List<RelationalParameter> parameters) {
return new RelationalParameters(parameters);
}
/**
* Custom {@link Parameter} implementation.
*
* @author Mark Paluch
*/
public static class RelationalParameter extends Parameter {
/**
* Creates a new {@link RelationalParameter}.
*
* @param parameter must not be {@literal null}.
*/
RelationalParameter(MethodParameter parameter) {
super(parameter);
}
}
}

View File

@@ -1,62 +0,0 @@
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.relational.repository.query;
import java.util.Arrays;
import java.util.List;
import org.springframework.data.repository.query.Parameters;
import org.springframework.data.repository.query.ParametersParameterAccessor;
import org.springframework.data.repository.query.QueryMethod;
/**
* JDBC-specific {@link ParametersParameterAccessor}.
*
* @author Mark Paluch
*/
public class RelationalParametersParameterAccessor extends ParametersParameterAccessor
implements RelationalParameterAccessor {
private final List<Object> values;
/**
* Creates a new {@link RelationalParametersParameterAccessor}.
*
* @param method must not be {@literal null}.
* @param values must not be {@literal null}.
*/
public RelationalParametersParameterAccessor(QueryMethod method, Object[] values) {
super(method.getParameters(), values);
this.values = Arrays.asList(values);
}
/* (non-Javadoc)
* @see org.springframework.data.jdbc.repository.query.JdbcParameterAccessor#getValues()
*/
@Override
public Object[] getValues() {
return values.toArray();
}
/* (non-Javadoc)
* @see org.springframework.data.jdbc.repository.query.RelationalParameterAccessor#getBindableParameters()
*/
@Override
public Parameters<?, ?> getBindableParameters() {
return getParameters().getBindableParameters();
}
}

View File

@@ -1,62 +0,0 @@
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.relational.repository.query;
import lombok.Getter;
import org.springframework.data.relational.core.mapping.RelationalPersistentEntity;
import org.springframework.util.Assert;
/**
* Default implementation of {@link RelationalEntityMetadata}.
*
* @author Mark Paluch
*/
public class SimpleRelationalEntityMetadata<T> implements RelationalEntityMetadata<T> {
private final Class<T> type;
private final @Getter RelationalPersistentEntity<?> tableEntity;
/**
* Creates a new {@link SimpleRelationalEntityMetadata} using the given type and {@link RelationalPersistentEntity} to
* use for table lookups.
*
* @param type must not be {@literal null}.
* @param tableEntity must not be {@literal null}.
*/
public SimpleRelationalEntityMetadata(Class<T> type, RelationalPersistentEntity<?> tableEntity) {
Assert.notNull(type, "Type must not be null!");
Assert.notNull(tableEntity, "Table entity must not be null!");
this.type = type;
this.tableEntity = tableEntity;
}
/* (non-Javadoc)
* @see org.springframework.data.repository.core.EntityMetadata#getJavaType()
*/
public Class<T> getJavaType() {
return type;
}
/* (non-Javadoc)
* @see org.springframework.data.jdbc.repository.query.RelationalEntityMetadata#getTableName()
*/
public String getTableName() {
return tableEntity.getTableName();
}
}

View File

@@ -1,7 +0,0 @@
/**
* Query support for relational database repositories.
*/
@NonNullApi
package org.springframework.data.relational.repository.query;
import org.springframework.lang.NonNullApi;

View File

@@ -1,111 +0,0 @@
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.relational.repository.support;
import org.springframework.data.relational.core.mapping.RelationalPersistentEntity;
import org.springframework.data.relational.repository.query.RelationalEntityInformation;
import org.springframework.data.repository.core.support.PersistentEntityInformation;
import org.springframework.lang.Nullable;
/**
* {@link RelationalEntityInformation} implementation using a {@link RelationalPersistentEntity} instance to lookup the
* necessary information. Can be configured with a custom table name.
* <p>
* Entity types that do not declare an explicit Id type fall back to {@link Long} as Id type.
*
* @author Mark Paluch
*/
public class MappingRelationalEntityInformation<T, ID> extends PersistentEntityInformation<T, ID>
implements RelationalEntityInformation<T, ID> {
private final RelationalPersistentEntity<T> entityMetadata;
private final @Nullable String customTableName;
private final Class<ID> fallbackIdType;
/**
* Creates a new {@link MappingRelationalEntityInformation} for the given {@link RelationalPersistentEntity}.
*
* @param entity must not be {@literal null}.
*/
public MappingRelationalEntityInformation(RelationalPersistentEntity<T> entity) {
this(entity, null, null);
}
/**
* Creates a new {@link MappingRelationalEntityInformation} for the given {@link RelationalPersistentEntity} and
* fallback identifier type.
*
* @param entity must not be {@literal null}.
* @param fallbackIdType can be {@literal null}.
*/
public MappingRelationalEntityInformation(RelationalPersistentEntity<T> entity, @Nullable Class<ID> fallbackIdType) {
this(entity, null, fallbackIdType);
}
/**
* Creates a new {@link MappingRelationalEntityInformation} for the given {@link RelationalPersistentEntity} and
* custom table name.
*
* @param entity must not be {@literal null}.
* @param customTableName can be {@literal null}.
*/
public MappingRelationalEntityInformation(RelationalPersistentEntity<T> entity, String customTableName) {
this(entity, customTableName, null);
}
/**
* Creates a new {@link MappingRelationalEntityInformation} for the given {@link RelationalPersistentEntity},
* collection name and identifier type.
*
* @param entity must not be {@literal null}.
* @param customTableName can be {@literal null}.
* @param idType can be {@literal null}.
*/
@SuppressWarnings("unchecked")
private MappingRelationalEntityInformation(RelationalPersistentEntity<T> entity, @Nullable String customTableName,
@Nullable Class<ID> idType) {
super(entity);
this.entityMetadata = entity;
this.customTableName = customTableName;
this.fallbackIdType = idType != null ? idType : (Class<ID>) Long.class;
}
/* (non-Javadoc)
* @see org.springframework.data.relational.repository.query.RelationalEntityInformation#getTableName()
*/
public String getTableName() {
return customTableName == null ? entityMetadata.getTableName() : customTableName;
}
public String getIdAttribute() {
return entityMetadata.getRequiredIdProperty().getName();
}
/* (non-Javadoc)
* @see org.springframework.data.repository.core.support.PersistentEntityInformation#getIdType()
*/
@Override
public Class<ID> getIdType() {
if (this.entityMetadata.hasIdProperty()) {
return super.getIdType();
}
return fallbackIdType;
}
}

View File

@@ -1,7 +0,0 @@
/**
* Support infrastructure for query derivation of relational database repositories.
*/
@NonNullApi
package org.springframework.data.relational.repository.support;
import org.springframework.lang.NonNullApi;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017-2018 the original author or authors.
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.jdbc.degraph;
package org.springframework.data.r2dbc;
import static de.schauderhaft.degraph.check.JCheck.*;
import static org.junit.Assert.*;

View File

@@ -28,7 +28,7 @@ import org.junit.Test;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jdbc.testing.R2dbcIntegrationTestSupport;
import org.springframework.data.r2dbc.testing.R2dbcIntegrationTestSupport;
import org.springframework.data.relational.core.mapping.Table;
import org.springframework.jdbc.core.JdbcTemplate;

View File

@@ -30,7 +30,7 @@ import java.util.concurrent.ArrayBlockingQueue;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.jdbc.testing.R2dbcIntegrationTestSupport;
import org.springframework.data.r2dbc.testing.R2dbcIntegrationTestSupport;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.NoTransactionException;

View File

@@ -33,12 +33,12 @@ import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.annotation.Id;
import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.jdbc.testing.R2dbcIntegrationTestSupport;
import org.springframework.data.r2dbc.function.DatabaseClient;
import org.springframework.data.r2dbc.function.DefaultReactiveDataAccessStrategy;
import org.springframework.data.r2dbc.function.TransactionalDatabaseClient;
import org.springframework.data.r2dbc.repository.query.Query;
import org.springframework.data.r2dbc.repository.support.R2dbcRepositoryFactory;
import org.springframework.data.r2dbc.testing.R2dbcIntegrationTestSupport;
import org.springframework.data.relational.core.conversion.BasicRelationalConverter;
import org.springframework.data.relational.core.mapping.RelationalMappingContext;
import org.springframework.data.relational.core.mapping.Table;

View File

@@ -27,7 +27,6 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.projection.ProjectionFactory;
import org.springframework.data.projection.SpelAwareProxyProjectionFactory;
import org.springframework.data.r2dbc.function.DatabaseClient;

View File

@@ -33,7 +33,7 @@ import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.annotation.Id;
import org.springframework.data.jdbc.testing.R2dbcIntegrationTestSupport;
import org.springframework.data.r2dbc.testing.R2dbcIntegrationTestSupport;
import org.springframework.data.r2dbc.function.DatabaseClient;
import org.springframework.data.r2dbc.function.DefaultReactiveDataAccessStrategy;
import org.springframework.data.r2dbc.function.convert.MappingR2dbcConverter;

View File

@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.jdbc.testing;
package org.springframework.data.r2dbc.testing;
import lombok.Builder;

View File

@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.jdbc.testing;
package org.springframework.data.r2dbc.testing;
import io.r2dbc.postgresql.PostgresqlConnectionConfiguration;
import io.r2dbc.postgresql.PostgresqlConnectionFactory;
@@ -23,7 +23,7 @@ import javax.sql.DataSource;
import org.junit.ClassRule;
import org.postgresql.ds.PGSimpleDataSource;
import org.springframework.data.jdbc.testing.ExternalDatabase.ProvidedDatabase;
import org.springframework.data.r2dbc.testing.ExternalDatabase.ProvidedDatabase;
import org.springframework.jdbc.core.JdbcTemplate;
/**

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %5p %40.40c:%4L - %m%n</pattern>
</encoder>
</appender>
<!--<logger name="org.springframework.data" level="info" />-->
<!--<logger name="org.springframework.jdbc.core" level="trace" />-->
<root level="warn">
<appender-ref ref="console"/>
</root>
</configuration>