├── README.adoc ├── benchmark ├── relational │ ├── src │ │ └── main │ │ │ ├── resources │ │ │ ├── application-jdbc.properties │ │ │ ├── application-jpa.properties │ │ │ ├── application-r2dbc.properties │ │ │ ├── schema-postgres.sql │ │ │ ├── schema-h2.sql │ │ │ ├── application-h2-in-memory.properties │ │ │ ├── data-postgres.sql │ │ │ ├── data-h2.sql │ │ │ ├── application-h2.properties │ │ │ └── application-postgres.properties │ │ │ └── java │ │ │ └── org │ │ │ └── springframework │ │ │ └── data │ │ │ └── microbenchmark │ │ │ ├── jdbc │ │ │ ├── BenchmarkMain.java │ │ │ ├── Book.java │ │ │ ├── JdbcBookRepository.java │ │ │ ├── JdbcBenchmark.java │ │ │ └── JdbcFixture.java │ │ │ ├── jpa │ │ │ ├── Book.java │ │ │ ├── JpaBookRepository.java │ │ │ ├── JpaFixture.java │ │ │ └── JpaBenchmark.java │ │ │ ├── r2dbc │ │ │ ├── Book.java │ │ │ ├── R2dbcFixture.java │ │ │ ├── R2dbcBookRepository.java │ │ │ └── R2dbcBenchmark.java │ │ │ └── FixtureUtils.java │ ├── pom.xml │ └── readme.adoc ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── support │ ├── src │ │ └── main │ │ │ ├── resources │ │ │ ├── META-INF │ │ │ │ └── services │ │ │ │ │ └── jmh.mbr.core.ResultsWriterFactory │ │ │ └── logback.xml │ │ │ └── java │ │ │ └── org │ │ │ └── springframework │ │ │ └── data │ │ │ └── microbenchmark │ │ │ └── common │ │ │ ├── MicrobenchmarkResultsWriterFactory.java │ │ │ ├── AbstractMicrobenchmark.java │ │ │ ├── HttpResultsWriter.java │ │ │ └── MongoResultsWriter.java │ └── pom.xml ├── mongodb │ ├── src │ │ └── main │ │ │ └── java │ │ │ └── org │ │ │ └── springframework │ │ │ └── data │ │ │ └── microbenchmark │ │ │ └── mongodb │ │ │ ├── Constants.java │ │ │ ├── MongoDbBookRepository.java │ │ │ ├── Book.java │ │ │ ├── MongoDbFixture.java │ │ │ ├── convert │ │ │ ├── DbRefMappingBenchmark.java │ │ │ └── MappingMongoConverterBenchmark.java │ │ │ ├── CallbacksBenchmark.java │ │ │ ├── MongoDbBenchmark.java │ │ │ ├── AfterConvertCallbacksBenchmark.java │ │ │ └── ProjectionsBenchmark.java │ └── pom.xml ├── commons │ ├── src │ │ └── main │ │ │ ├── kotlin │ │ │ └── org │ │ │ │ └── springframework │ │ │ │ └── data │ │ │ │ └── microbenchmark │ │ │ │ └── commons │ │ │ │ └── convert │ │ │ │ └── MyDataClass.kt │ │ │ └── java │ │ │ └── org │ │ │ └── springframework │ │ │ └── data │ │ │ └── microbenchmark │ │ │ └── commons │ │ │ └── convert │ │ │ ├── DefaultTypeMapperBenchmark.java │ │ │ └── TypicalEntityReaderBenchmark.java │ └── pom.xml ├── redis │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── org │ │ └── springframework │ │ └── data │ │ └── microbenchmark │ │ └── redis │ │ └── ReactiveRedisTemplateBenchmark.java ├── README.md ├── pom.xml ├── mvnw.cmd └── mvnw ├── .gitignore └── LICENSE.txt /README.adoc: -------------------------------------------------------------------------------- 1 | = Spring Data Development Tools 2 | 3 | A collection of tools to support Spring Data development. -------------------------------------------------------------------------------- /benchmark/relational/src/main/resources/application-jdbc.properties: -------------------------------------------------------------------------------- 1 | spring.data.jpa.repositories.enabled=false 2 | 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | .settings/ 3 | .project 4 | .classpath 5 | .factorypath 6 | .springBeans 7 | .idea/ 8 | *.iml 9 | build/ 10 | -------------------------------------------------------------------------------- /benchmark/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spring-projects/spring-data-dev-tools/HEAD/benchmark/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /benchmark/relational/src/main/resources/application-jpa.properties: -------------------------------------------------------------------------------- 1 | spring.jpa.hibernate.ddl-auto=create-drop 2 | spring.data.jdbc.repositories.enabled=false 3 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/resources/application-r2dbc.properties: -------------------------------------------------------------------------------- 1 | spring.data.jpa.repositories.enabled=false 2 | spring.data.jdbc.repositories.enabled=false 3 | -------------------------------------------------------------------------------- /benchmark/support/src/main/resources/META-INF/services/jmh.mbr.core.ResultsWriterFactory: -------------------------------------------------------------------------------- 1 | org.springframework.data.microbenchmark.common.MicrobenchmarkResultsWriterFactory 2 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/resources/schema-postgres.sql: -------------------------------------------------------------------------------- 1 | drop table if exists Book; 2 | create table Book ( 3 | id serial primary key, 4 | title varchar(255), 5 | pages integer not null 6 | ); 7 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/resources/schema-h2.sql: -------------------------------------------------------------------------------- 1 | drop table Book if exists; 2 | create table Book ( 3 | id bigint not null auto_increment, 4 | title varchar(255), 5 | pages integer not null, 6 | primary key (id) 7 | ); 8 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/resources/application-h2-in-memory.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:h2:mem:benchmark;DB_CLOSE_DELAY=-1 2 | spring.sql.init.platform=h2 3 | spring.r2dbc.platform=h2 4 | 5 | 6 | logging.level.org.springframework.boot.autoconfigure=DEBUG -------------------------------------------------------------------------------- /benchmark/support/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | %d %5p %40.40c:%4L - %m%n 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/resources/data-postgres.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO Book(title, pages) VALUES ('title0', 0); 2 | INSERT INTO Book(title, pages) VALUES ('title1', 1); 3 | INSERT INTO Book(title, pages) VALUES ('title2', 2); 4 | INSERT INTO Book(title, pages) VALUES ('title3', 3); 5 | INSERT INTO Book(title, pages) VALUES ('title4', 4); 6 | INSERT INTO Book(title, pages) VALUES ('title5', 5); 7 | INSERT INTO Book(title, pages) VALUES ('title6', 6); 8 | INSERT INTO Book(title, pages) VALUES ('title7', 7); 9 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/resources/data-h2.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO Book (title, pages) VALUES ('title1', 1); 2 | INSERT INTO Book (title, pages) VALUES ('title0', 0); 3 | INSERT INTO Book (title, pages) VALUES ('title2', 2); 4 | INSERT INTO Book (title, pages) VALUES ('title3', 3); 5 | INSERT INTO Book (title, pages) VALUES ('title4', 4); 6 | INSERT INTO Book (title, pages) VALUES ('title5', 5); 7 | INSERT INTO Book (title, pages) VALUES ('title6', 6); 8 | INSERT INTO Book (title, pages) VALUES ('title7', 7); 9 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/resources/application-h2.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:h2:tcp://localhost:9092/~/benchmark 2 | spring.datasource.username=sa 3 | spring.datasource.password= 4 | spring.sql.init.platform=h2 5 | spring.sql.init.mode=always 6 | 7 | spring.r2dbc.url=r2dbc:h2:tcp://localhost:9092/~/benchmark 8 | spring.r2dbc.username=sa 9 | spring.r2dbc.password= 10 | spring.r2dbc.platform=h2 11 | spring.r2dbc.initialization-mode=always 12 | 13 | logging.level.org.springframework.boot.autoconfigure=DEBUG -------------------------------------------------------------------------------- /benchmark/relational/src/main/resources/application-postgres.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:postgresql://localhost:5455/benchmark 2 | # this is intentionally non standard property user instead of username, since we are using PGSimpleDatasource, which has a user, but no username property 3 | spring.datasource.user=postgres 4 | spring.datasource.password=secret 5 | spring.sql.init.platform=postgres 6 | spring.sql.init.mode=always 7 | 8 | spring.r2dbc.url=r2dbc:postgresql://localhost:5432/benchmark 9 | spring.r2dbc.platform=postgres 10 | spring.r2dbc.username=postgres 11 | spring.r2dbc.password=secret 12 | spring.r2dbc.initialization-mode=always 13 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/java/org/springframework/data/microbenchmark/jdbc/BenchmarkMain.java: -------------------------------------------------------------------------------- 1 | package org.springframework.data.microbenchmark.jdbc; 2 | 3 | import org.openjdk.jmh.infra.Blackhole; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | public class BenchmarkMain { 7 | public static void main(String[] args) throws Exception { 8 | JdbcBenchmark jdbcBenchmark = new JdbcBenchmark(); 9 | jdbcBenchmark.profile = "postgres"; 10 | jdbcBenchmark.setUp(); 11 | jdbcBenchmark.convertWithSpringData(new Blackhole("Today's password is swordfish. I understand instantiating Blackholes directly is dangerous.")); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /benchmark/mongodb/src/main/java/org/springframework/data/microbenchmark/mongodb/Constants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.mongodb; 17 | 18 | import lombok.experimental.UtilityClass; 19 | 20 | /** 21 | * @author Oliver Drotbohm 22 | */ 23 | @UtilityClass 24 | class Constants { 25 | 26 | public static final int NUMBER_OF_BOOKS = 8; 27 | } 28 | -------------------------------------------------------------------------------- /benchmark/commons/src/main/kotlin/org/springframework/data/microbenchmark/commons/convert/MyDataClass.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.commons.convert 17 | 18 | /** 19 | * @author Mark Paluch 20 | */ 21 | data class MyDataClass(val firstname: String, val lastname: String) 22 | 23 | data class MyDataClassWithDefaulting(val firstname: String, val lastname: String, val foo: Int = 42) 24 | -------------------------------------------------------------------------------- /benchmark/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.5/apache-maven-3.9.5-bin.zip 18 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar 19 | -------------------------------------------------------------------------------- /benchmark/redis/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 4.0.0 7 | 8 | 9 | org.springframework.data.benchmark 10 | spring-data-benchmark-parent 11 | 3.3.0-SNAPSHOT 12 | 13 | 14 | spring-data-benchmark-redis 15 | 16 | Spring Data Benchmarks - Redis Microbenchmarks 17 | 18 | 19 | 20 | 21 | ${project.groupId} 22 | spring-data-benchmark-support 23 | 24 | 25 | 26 | org.springframework.data 27 | spring-data-redis 28 | 29 | 30 | 31 | io.lettuce 32 | lettuce-core 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/java/org/springframework/data/microbenchmark/jdbc/Book.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.jdbc; 17 | 18 | import lombok.AllArgsConstructor; 19 | import lombok.Data; 20 | 21 | import org.springframework.data.annotation.Id; 22 | import org.springframework.data.relational.core.mapping.Table; 23 | 24 | /** 25 | * @author Oliver Drotbohm 26 | */ 27 | @Data 28 | @AllArgsConstructor 29 | @Table 30 | public class Book { 31 | 32 | private @Id Long id; 33 | private String title; 34 | private int pages; 35 | } 36 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/java/org/springframework/data/microbenchmark/jpa/Book.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.jpa; 17 | 18 | import lombok.AllArgsConstructor; 19 | import lombok.Data; 20 | import lombok.NoArgsConstructor; 21 | 22 | import jakarta.persistence.Entity; 23 | import jakarta.persistence.GeneratedValue; 24 | import jakarta.persistence.Id; 25 | 26 | /** 27 | * @author Oliver Drotbohm 28 | */ 29 | @Data 30 | @Entity 31 | @AllArgsConstructor 32 | @NoArgsConstructor 33 | public class Book { 34 | 35 | private @GeneratedValue @Id Long id; 36 | private String title; 37 | private int pages; 38 | } 39 | -------------------------------------------------------------------------------- /benchmark/commons/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 4.0.0 6 | 7 | 8 | org.springframework.data.benchmark 9 | spring-data-benchmark-parent 10 | 3.3.0-SNAPSHOT 11 | 12 | 13 | spring-data-benchmark-commons 14 | 15 | Spring Data Benchmarks - Commons Microbenchmarks 16 | 17 | 18 | 19 | 20 | ${project.groupId} 21 | spring-data-benchmark-support 22 | 23 | 24 | 25 | org.springframework.data 26 | spring-data-commons 27 | 28 | 29 | 30 | org.jetbrains.kotlin 31 | kotlin-stdlib-jdk8 32 | ${kotlin} 33 | 34 | 35 | 36 | org.jetbrains.kotlin 37 | kotlin-reflect 38 | ${kotlin} 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /benchmark/mongodb/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 4.0.0 6 | 7 | 8 | org.springframework.data.benchmark 9 | spring-data-benchmark-parent 10 | 3.3.0-SNAPSHOT 11 | 12 | 13 | spring-data-benchmark-mongodb 14 | 15 | Spring Data Benchmarks - MongoDB Microbenchmarks 16 | 17 | 18 | 19 | 20 | ${project.groupId} 21 | spring-data-benchmark-support 22 | 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-data-mongodb 27 | 28 | 29 | 30 | org.mockito 31 | mockito-core 32 | 33 | 34 | 35 | de.flapdoodle.embed 36 | de.flapdoodle.embed.mongo 37 | 4.12.2 38 | runtime 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /benchmark/mongodb/src/main/java/org/springframework/data/microbenchmark/mongodb/MongoDbBookRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.mongodb; 17 | 18 | import java.util.Optional; 19 | 20 | import org.bson.types.ObjectId; 21 | import org.springframework.data.mongodb.repository.Query; 22 | import org.springframework.data.repository.CrudRepository; 23 | 24 | /** 25 | * @author Oliver Drotbohm 26 | */ 27 | interface MongoDbBookRepository extends CrudRepository { 28 | 29 | @Query("{ \"title\" : $0 }") 30 | Book findDeclaredByTitle(String title); 31 | 32 | Book findDerivedByTitle(String title); 33 | 34 | Optional findOptionalDerivedByTitle(String title); 35 | } 36 | -------------------------------------------------------------------------------- /benchmark/support/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 4.0.0 6 | 7 | 8 | org.springframework.data.benchmark 9 | spring-data-benchmark-parent 10 | 3.3.0-SNAPSHOT 11 | 12 | 13 | spring-data-benchmark-support 14 | 15 | Spring Data Benchmarks - Support 16 | 17 | SpringDataBenchmarkSupport 18 | 19 | 20 | 21 | 22 | 23 | org.springframework.data 24 | spring-data-mongodb 25 | 26 | 27 | 28 | org.mongodb 29 | mongodb-driver-sync 30 | 31 | 32 | 33 | com.github.mp911de.microbenchmark-runner 34 | microbenchmark-runner-junit4 35 | 36 | 37 | 38 | net.minidev 39 | json-smart 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /benchmark/support/src/main/java/org/springframework/data/microbenchmark/common/MicrobenchmarkResultsWriterFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.common; 17 | 18 | import jmh.mbr.core.ResultsWriter; 19 | import jmh.mbr.core.ResultsWriterFactory; 20 | 21 | /** 22 | * {@link ResultsWriterFactory} plugin via {@link java.util.ServiceLoader}. 23 | * 24 | * @author Mark Paluch 25 | */ 26 | public class MicrobenchmarkResultsWriterFactory implements ResultsWriterFactory { 27 | 28 | @Override 29 | public ResultsWriter forUri(String uri) { 30 | 31 | if (uri.startsWith("http")) { 32 | return new HttpResultsWriter(uri); 33 | } 34 | 35 | if (uri.startsWith("mongo")) { 36 | return new MongoResultsWriter(uri); 37 | } 38 | 39 | return null; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/java/org/springframework/data/microbenchmark/r2dbc/Book.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.r2dbc; 17 | 18 | import lombok.AccessLevel; 19 | import lombok.RequiredArgsConstructor; 20 | import lombok.Value; 21 | import lombok.With; 22 | 23 | import org.springframework.data.annotation.Id; 24 | import org.springframework.data.annotation.PersistenceConstructor; 25 | 26 | /** 27 | * @author Oliver Drotbohm 28 | */ 29 | @Value 30 | @RequiredArgsConstructor(access = AccessLevel.PACKAGE, onConstructor = @__(@PersistenceConstructor)) 31 | class Book { 32 | 33 | @With(AccessLevel.PACKAGE) @Id Long id; 34 | String title; 35 | int pages; 36 | 37 | public Book(String title, int pages) { 38 | 39 | this.id = null; 40 | this.title = title; 41 | this.pages = pages; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /benchmark/mongodb/src/main/java/org/springframework/data/microbenchmark/mongodb/Book.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.mongodb; 17 | 18 | import lombok.AllArgsConstructor; 19 | import lombok.Value; 20 | 21 | import org.bson.types.ObjectId; 22 | 23 | import org.springframework.data.annotation.Id; 24 | import org.springframework.data.annotation.PersistenceConstructor; 25 | import org.springframework.data.mongodb.core.mapping.Document; 26 | 27 | /** 28 | * @author Oliver Drotbohm 29 | */ 30 | @Value 31 | @Document 32 | @AllArgsConstructor(onConstructor = @__(@PersistenceConstructor)) 33 | public class Book { 34 | 35 | @Id ObjectId id; 36 | String title; 37 | int pages; 38 | 39 | public Book(String title, int pages) { 40 | 41 | this.id = ObjectId.get(); 42 | this.title = title; 43 | this.pages = pages; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/java/org/springframework/data/microbenchmark/r2dbc/R2dbcFixture.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.r2dbc; 17 | 18 | import lombok.Getter; 19 | 20 | import org.springframework.boot.autoconfigure.SpringBootApplication; 21 | import org.springframework.context.ConfigurableApplicationContext; 22 | import org.springframework.data.microbenchmark.FixtureUtils; 23 | 24 | /** 25 | * Test fixture for JDBC and Spring Data JDBC benchmarks. 26 | * 27 | * @author Oliver Drotbohm 28 | */ 29 | public class R2dbcFixture { 30 | 31 | private final @Getter ConfigurableApplicationContext context; 32 | 33 | public R2dbcFixture(String database) { 34 | this.context = FixtureUtils.createContext(R2dbcApplication.class, "r2dbc", database); 35 | } 36 | 37 | @SpringBootApplication 38 | static class R2dbcApplication {} 39 | } 40 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/java/org/springframework/data/microbenchmark/FixtureUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark; 17 | 18 | import lombok.experimental.UtilityClass; 19 | 20 | import java.util.Arrays; 21 | import java.util.Collections; 22 | 23 | import org.springframework.boot.SpringApplication; 24 | import org.springframework.context.ConfigurableApplicationContext; 25 | 26 | @UtilityClass 27 | public class FixtureUtils { 28 | 29 | public static final int NUMBER_OF_BOOKS = 8; 30 | 31 | public static ConfigurableApplicationContext createContext(Class configuration, String api, String database) { 32 | 33 | SpringApplication application = new SpringApplication(); 34 | application.addPrimarySources(Collections.singletonList(configuration)); 35 | application.setLazyInitialization(true); 36 | application.setAdditionalProfiles(api, database); 37 | 38 | System.out.println("Activating profiles: " + Arrays.asList(api, database).toString()); 39 | 40 | return application.run(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/java/org/springframework/data/microbenchmark/jpa/JpaBookRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.jpa; 17 | 18 | import java.util.Optional; 19 | 20 | import org.springframework.data.jpa.repository.Query; 21 | import org.springframework.data.repository.CrudRepository; 22 | import org.springframework.transaction.annotation.Transactional; 23 | 24 | /** 25 | * @author Oliver Drotbohm 26 | */ 27 | interface JpaBookRepository extends CrudRepository { 28 | 29 | static final String BY_TITLE_JPQL = "select b from Book b where b.title = :title"; 30 | 31 | @Query(BY_TITLE_JPQL) 32 | Book findDeclaredByTitle(String title); 33 | 34 | @Transactional(readOnly = true) 35 | @Query(BY_TITLE_JPQL) 36 | Book findTransactionalDeclaredByTitle(String title); 37 | 38 | Book findDerivedByTitle(String title); 39 | 40 | @Transactional(readOnly = true) 41 | Book findTransactionalDerivedByTitle(String title); 42 | 43 | Optional findOptionalDerivedByTitle(String title); 44 | } 45 | -------------------------------------------------------------------------------- /benchmark/support/src/main/java/org/springframework/data/microbenchmark/common/AbstractMicrobenchmark.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.common; 17 | 18 | import jmh.mbr.junit4.Microbenchmark; 19 | 20 | import org.junit.runner.RunWith; 21 | import org.openjdk.jmh.annotations.Fork; 22 | import org.openjdk.jmh.annotations.Measurement; 23 | import org.openjdk.jmh.annotations.Scope; 24 | import org.openjdk.jmh.annotations.State; 25 | import org.openjdk.jmh.annotations.Warmup; 26 | 27 | /** 28 | * Base class for microbenchmarks providing default JMH settings and allowing execution through JUnit. 29 | * 30 | * @author Christoph Strobl 31 | * @author Mark Paluch 32 | * @see Microbenchmark 33 | */ 34 | @Warmup(iterations = 10, time = 2) 35 | @Measurement(iterations = 10, time = 2) 36 | @Fork(value = 1, jvmArgs = { "-server", "-XX:+HeapDumpOnOutOfMemoryError", "-Xms1024m", "-Xmx1024m", 37 | "-XX:MaxDirectMemorySize=1024m", "-noverify" }) 38 | @State(Scope.Thread) 39 | @RunWith(Microbenchmark.class) 40 | public abstract class AbstractMicrobenchmark { 41 | 42 | } 43 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/java/org/springframework/data/microbenchmark/r2dbc/R2dbcBookRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.r2dbc; 17 | 18 | import reactor.core.publisher.Flux; 19 | import reactor.core.publisher.Mono; 20 | 21 | import org.springframework.data.r2dbc.repository.Query; 22 | import org.springframework.data.r2dbc.repository.R2dbcRepository; 23 | import org.springframework.transaction.annotation.Propagation; 24 | import org.springframework.transaction.annotation.Transactional; 25 | 26 | /** 27 | * A repository for {@link Book} instances. 28 | * 29 | * @author Oliver Drotbohm 30 | */ 31 | interface R2dbcBookRepository extends R2dbcRepository { 32 | 33 | static final String BY_TITLE = "SELECT id, title, pages FROM Book where title = :title"; 34 | 35 | @Transactional(propagation = Propagation.NOT_SUPPORTED) 36 | Flux findAll(); 37 | 38 | @Query(BY_TITLE) 39 | Mono findByTitle(String title); 40 | 41 | @Transactional(readOnly = true) 42 | @Query(BY_TITLE) 43 | Mono findTransactionalByTitle(String title); 44 | } 45 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/java/org/springframework/data/microbenchmark/jdbc/JdbcBookRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.jdbc; 17 | 18 | import java.util.Optional; 19 | 20 | import org.springframework.data.jdbc.repository.query.Query; 21 | import org.springframework.data.repository.CrudRepository; 22 | import org.springframework.transaction.annotation.Propagation; 23 | import org.springframework.transaction.annotation.Transactional; 24 | 25 | /** 26 | * A repository for {@link Book} instances. 27 | * 28 | * @author Oliver Drotbohm 29 | */ 30 | interface JdbcBookRepository extends CrudRepository { 31 | 32 | static final String BY_TITLE = "SELECT id, title, pages FROM Book where title = :title"; 33 | 34 | @Transactional(propagation = Propagation.NOT_SUPPORTED) 35 | Iterable findAll(); 36 | 37 | @Query(BY_TITLE) 38 | Book findByTitle(String title); 39 | 40 | @Transactional(readOnly = true) 41 | @Query(BY_TITLE) 42 | Book findTransactionalByTitle(String title); 43 | 44 | @Query(BY_TITLE) 45 | Optional findOptionalByTitle(String title); 46 | } 47 | -------------------------------------------------------------------------------- /benchmark/mongodb/src/main/java/org/springframework/data/microbenchmark/mongodb/MongoDbFixture.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.mongodb; 17 | 18 | import lombok.Getter; 19 | 20 | import java.util.Collections; 21 | import java.util.stream.IntStream; 22 | 23 | import org.springframework.boot.SpringApplication; 24 | import org.springframework.boot.autoconfigure.SpringBootApplication; 25 | import org.springframework.context.ConfigurableApplicationContext; 26 | import org.springframework.data.mongodb.core.MongoOperations; 27 | 28 | /** 29 | * @author Oliver Drotbohm 30 | */ 31 | class MongoDbFixture { 32 | 33 | private final @Getter ConfigurableApplicationContext context; 34 | 35 | MongoDbFixture() { 36 | 37 | SpringApplication application = new SpringApplication(); 38 | application.addPrimarySources(Collections.singletonList(MongoDbApplication.class)); 39 | application.setAdditionalProfiles("jpa"); 40 | application.setLazyInitialization(true); 41 | 42 | this.context = application.run(); 43 | 44 | MongoOperations operations = context.getBean(MongoOperations.class); 45 | 46 | operations.dropCollection(Book.class); 47 | 48 | IntStream.range(0, Constants.NUMBER_OF_BOOKS) // 49 | .mapToObj(it -> new Book("title" + it, it)) // 50 | .forEach(operations::save); 51 | } 52 | 53 | @SpringBootApplication 54 | static class MongoDbApplication {} 55 | } 56 | -------------------------------------------------------------------------------- /benchmark/relational/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 4.0.0 6 | 7 | 8 | org.springframework.data.benchmark 9 | spring-data-benchmark-parent 10 | 3.3.0-SNAPSHOT 11 | 12 | 13 | spring-data-benchmark-relational 14 | 15 | Spring Data Benchmarks - Relational Microbenchmarks 16 | 17 | 18 | 19 | 20 | ${project.groupId} 21 | spring-data-benchmark-support 22 | 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-data-jpa 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-data-jdbc 32 | 33 | 34 | 35 | com.h2database 36 | h2 37 | 38 | 39 | 40 | org.postgresql 41 | postgresql 42 | 43 | 44 | 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-starter-data-r2dbc 49 | 50 | 51 | 52 | io.r2dbc 53 | r2dbc-h2 54 | 55 | 56 | 57 | org.postgresql 58 | r2dbc-postgresql 59 | 60 | 61 | 62 | 63 | 64 | org.mockito 65 | mockito-core 66 | 67 | 68 | 69 | com.mockrunner 70 | mockrunner-jdbc 71 | 2.0.1 72 | 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /benchmark/relational/readme.adoc: -------------------------------------------------------------------------------- 1 | = Benchmarks for relational data access with Spring Data 2 | 3 | This benchmark evaluates various options of relation data access in the Spring Data project family: 4 | 5 | - JDBC and Spring Data JDBC 6 | - JPA and Spring Data JPA 7 | 8 | The primary purpose of the benchmark is to help the team detect degradations in performance quickly or verify optimizations made in various areas of the libraries. 9 | It also helps justifying differences between numbers in rather clean room contexts (an embedded database) and scenarios that use a more realistic setup like a locally running database. 10 | That difference alone will help reasoning about the real-world impact of an optimization or degradation. 11 | 12 | == Benchmark model 13 | 14 | The benchmarks use a very simple model of a book with a title and pages attribute. 15 | We deliberately chose a simple model as the benchmarks are supposed to measure the overhead the Spring Data mapping and repository infrastructure adds on top of the raw JDBC and JPA alternatives. 16 | There are two major benchmark operations: 17 | 18 | 1. Finding all books (8 items) 19 | 2. Finding a single book by title. 20 | 21 | There are different flavors of those operations to measure the impact of different setups to execute them: 22 | 23 | - the effect of read-only transactions in the find all case 24 | - the difference between derived and declared queries in JPA 25 | 26 | == Infrastructure 27 | 28 | The benchmarks are run against the following databases: 29 | 30 | - In-memory H2 31 | - A locally running H2 (port 9092, database name `benchmark`, user `sa`, empty password). 32 | You may start such a server by running 33 | + 34 | ``` 35 | java -cp ~/.m2/repository/com/h2database/h2/2.2.224/h2-2.2.224.jar org.h2.tools.Server -ifNotExists 36 | ``` 37 | assuming you have a local maven repo in the default location. 38 | - A locally running Postgres (port 5455, database name `benchmark`, user: postgres, password: secret). You may start such a server by running 39 | + 40 | ``` 41 | docker run --name myPostgresDb -p 5455:5432 -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=benchmark -d postgres 42 | ``` 43 | 44 | The settings can be adapted by tweaking corresponding `application-$database.properties` file in `src/main/resources`. 45 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/java/org/springframework/data/microbenchmark/jpa/JpaFixture.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.jpa; 17 | 18 | import lombok.Getter; 19 | 20 | import java.util.function.Consumer; 21 | import java.util.stream.IntStream; 22 | 23 | import jakarta.persistence.EntityManager; 24 | 25 | import org.springframework.boot.autoconfigure.SpringBootApplication; 26 | import org.springframework.context.ConfigurableApplicationContext; 27 | import org.springframework.data.microbenchmark.FixtureUtils; 28 | import org.springframework.transaction.PlatformTransactionManager; 29 | import org.springframework.transaction.TransactionStatus; 30 | import org.springframework.transaction.support.DefaultTransactionDefinition; 31 | 32 | /** 33 | * Test fixture for JPA and Spring Data JPA benchmarks. 34 | * 35 | * @author Oliver Drotbohm 36 | */ 37 | class JpaFixture { 38 | 39 | private final @Getter ConfigurableApplicationContext context; 40 | 41 | JpaFixture(String database) { 42 | 43 | this.context = FixtureUtils.createContext(JpaApplication.class, "jpa", database); 44 | 45 | withTransactionalEntityManager(em -> { 46 | 47 | IntStream.range(0, FixtureUtils.NUMBER_OF_BOOKS) // 48 | .mapToObj(it -> new Book(null, "title" + it, it)) // 49 | .forEach(em::persist); 50 | }); 51 | } 52 | 53 | private void withTransactionalEntityManager(Consumer consumer) { 54 | 55 | PlatformTransactionManager manager = context.getBean(PlatformTransactionManager.class); 56 | TransactionStatus status = manager.getTransaction(new DefaultTransactionDefinition()); 57 | 58 | EntityManager em = context.getBean(EntityManager.class); 59 | 60 | consumer.accept(em); 61 | 62 | em.flush(); 63 | manager.commit(status); 64 | em.close(); 65 | } 66 | 67 | @SpringBootApplication 68 | static class JpaApplication {} 69 | } 70 | -------------------------------------------------------------------------------- /benchmark/README.md: -------------------------------------------------------------------------------- 1 | # Benchmarks 2 | 3 | Benchmarks are based on [JMH](https://openjdk.java.net/projects/code-tools/jmh/). 4 | 5 | # Running Benchmarks 6 | 7 | To run the benchmarks with default settings use: 8 | 9 | ```bash 10 | mvn clean test 11 | ``` 12 | 13 | A basic report will be printed to the CLI. 14 | 15 | ```bash 16 | # Run complete. Total time: 00:00:15 17 | 18 | Benchmark Mode Cnt Score Error Units 19 | MappingMongoConverterBenchmark.readObject thrpt 10 1920157,631 ± 64310,809 ops/s 20 | MappingMongoConverterBenchmark.writeObject thrpt 10 782732,857 ± 53804,130 ops/s 21 | ``` 22 | 23 | ## Running all Benchmarks of a specific class 24 | 25 | To run all Benchmarks of a specific class, just provide its simple class name via the `benchmark` command line argument. 26 | 27 | ```bash 28 | mvn clean test -D benchmark=MappingMongoConverterBenchmark 29 | ``` 30 | 31 | ## Running a single Benchmark 32 | 33 | To run a single Benchmark provide its containing class simple name followed by `#` and the method name via the `benchmark` command line argument. 34 | 35 | ```bash 36 | mvn clean test -D benchmark=MappingMongoConverterBenchmark#readObjectWith2Properties 37 | ``` 38 | 39 | # Saving Benchmark Results 40 | 41 | A detailed benchmark report is stored in JSON format in the `/target/reports/performance` directory. 42 | To store the report in a different location use the `benchmarkReportDir` command line argument. 43 | 44 | ## MongoDB 45 | 46 | Results can be directly piped to MongoDB by providing a valid [Connection String](https://docs.mongodb.com/manual/reference/connection-string/) via the `publishTo` command line argument. 47 | 48 | ```bash 49 | mvn clean test -D publishTo=mongodb://127.0.0.1:27017 50 | ``` 51 | 52 | NOTE: If the uri does not explicitly define a database the default `spring-data-mongodb-benchmarks` is used. 53 | 54 | ## HTTP Endpoint 55 | 56 | The benchmark report can also be posted as `application/json` to an HTTP Endpoint by providing a valid URl via the `publishTo` command line argument. 57 | 58 | ```bash 59 | mvn clean test -D publishTo=http://127.0.0.1:8080/capture-benchmarks 60 | ``` 61 | 62 | # Customizing Benchmarks 63 | 64 | Following options can be set via command line. 65 | 66 | Option | Default Value 67 | --- | --- 68 | warmupIterations | 10 69 | warmupTime | 1 (seconds) 70 | measurementIterations | 10 71 | measurementTime | 1 (seconds) 72 | forks | 1 73 | benchmarkReportDir | /target/reports/performance (always relative to project root dir) 74 | benchmark | .* (single benchmark via `classname#benchmark`) 75 | publishTo | \[not set\] (mongodb-uri or http-endpoint) 76 | -------------------------------------------------------------------------------- /benchmark/commons/src/main/java/org/springframework/data/microbenchmark/commons/convert/DefaultTypeMapperBenchmark.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.commons.convert; 17 | 18 | import java.util.Collections; 19 | import java.util.Map; 20 | 21 | import org.openjdk.jmh.annotations.Benchmark; 22 | import org.springframework.data.convert.DefaultTypeMapper; 23 | import org.springframework.data.convert.TypeAliasAccessor; 24 | import org.springframework.data.mapping.Alias; 25 | import org.springframework.data.microbenchmark.common.AbstractMicrobenchmark; 26 | import org.springframework.data.util.ClassTypeInformation; 27 | import org.springframework.data.util.TypeInformation; 28 | 29 | /** 30 | * Benchmark for {@link DefaultTypeMapper}. 31 | * 32 | * @author Mark Paluch 33 | */ 34 | public class DefaultTypeMapperBenchmark extends AbstractMicrobenchmark { 35 | 36 | private static final DefaultTypeMapper> TYPE_MAPPER = new DefaultTypeMapper<>( 37 | StringTypeAliasAccessor.INSTANCE); 38 | 39 | private static final Map TYPED = Collections.singletonMap("_class", MySubType.class.getName()); 40 | private static final Map UNTYPED = Collections.emptyMap(); 41 | private static final TypeInformation TYPE_INFORMATION = ClassTypeInformation.from(MyType.class); 42 | 43 | @Benchmark 44 | public Object readTyped() { 45 | return TYPE_MAPPER.readType(TYPED); 46 | } 47 | 48 | @Benchmark 49 | public Object readTypedWithBaseType() { 50 | return TYPE_MAPPER.readType(TYPED, TYPE_INFORMATION); 51 | } 52 | 53 | @Benchmark 54 | public Object readUntyped() { 55 | return TYPE_MAPPER.readType(UNTYPED); 56 | } 57 | 58 | @Benchmark 59 | public Object readUntypedWithBaseType() { 60 | return TYPE_MAPPER.readType(UNTYPED, TYPE_INFORMATION); 61 | } 62 | 63 | static class MyType {} 64 | 65 | static class MySubType extends MyType {} 66 | 67 | enum StringTypeAliasAccessor implements TypeAliasAccessor> { 68 | 69 | INSTANCE; 70 | 71 | @Override 72 | public Alias readAliasFrom(Map source) { 73 | return Alias.ofNullable(source.get("_class")); 74 | } 75 | 76 | @Override 77 | public void writeTypeTo(Map sink, Object alias) { 78 | sink.put("_class", alias); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/java/org/springframework/data/microbenchmark/r2dbc/R2dbcBenchmark.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.r2dbc; 17 | 18 | import io.r2dbc.spi.Readable; 19 | import io.r2dbc.spi.Row; 20 | 21 | import java.util.function.Function; 22 | 23 | import org.openjdk.jmh.annotations.Benchmark; 24 | import org.openjdk.jmh.annotations.Param; 25 | import org.openjdk.jmh.annotations.Setup; 26 | import org.openjdk.jmh.infra.Blackhole; 27 | 28 | import org.springframework.context.ConfigurableApplicationContext; 29 | import org.springframework.data.microbenchmark.common.AbstractMicrobenchmark; 30 | import org.springframework.r2dbc.core.DatabaseClient; 31 | 32 | /** 33 | * Benchmark for R2DBC and Spring Data R2DBC 34 | * 35 | * @author Oliver Drotbohm 36 | */ 37 | public class R2dbcBenchmark extends AbstractMicrobenchmark { 38 | 39 | private static final String FIND_ALL_SQL = "SELECT id, title, pages FROM Book"; 40 | private static final String BY_TITLE_SQL = FIND_ALL_SQL + " where title = :title"; 41 | 42 | @Param({ /* "postgres", */ "h2-in-memory" /*, "h2" */ }) String profile; 43 | 44 | private DatabaseClient operations; 45 | private Function mapper; 46 | 47 | private R2dbcBookRepository repository; 48 | 49 | @Setup 50 | public void setUp() { 51 | 52 | R2dbcFixture fixture = new R2dbcFixture(profile); 53 | 54 | ConfigurableApplicationContext context = fixture.getContext(); 55 | 56 | this.operations = context.getBean(DatabaseClient.class); 57 | this.mapper = row -> new Book(row.get("id", Long.class), row.get("title", String.class), 58 | row.get("pages", Integer.class)); 59 | 60 | this.repository = context.getBean(R2dbcBookRepository.class); 61 | } 62 | 63 | @Benchmark 64 | public void findByTitle(Blackhole sink) { 65 | 66 | sink.consume(operations.sql(BY_TITLE_SQL) // 67 | .bind("title", "title0") // 68 | .map(mapper).one() // 69 | .block()); 70 | } 71 | 72 | @Benchmark 73 | public void findAll(Blackhole sink) { 74 | 75 | sink.consume(operations.sql(FIND_ALL_SQL) // 76 | .map(mapper) // 77 | .all() // 78 | .collectList() // 79 | .block()); 80 | } 81 | 82 | @Benchmark 83 | public void repositoryFindByTitle(Blackhole sink) { 84 | sink.consume(repository.findByTitle("title0").block()); 85 | } 86 | 87 | @Benchmark 88 | public void repositoryFindTransactionalByTitle(Blackhole sink) { 89 | sink.consume(repository.findTransactionalByTitle("title0").block()); 90 | } 91 | 92 | @Benchmark 93 | public void repositoryFindAll(Blackhole sink) { 94 | sink.consume(repository.findAll().collectList().block()); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /benchmark/mongodb/src/main/java/org/springframework/data/microbenchmark/mongodb/convert/DbRefMappingBenchmark.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.mongodb.convert; 17 | 18 | import static org.springframework.data.mongodb.core.query.Criteria.*; 19 | import static org.springframework.data.mongodb.core.query.Query.*; 20 | 21 | import lombok.Data; 22 | 23 | import java.util.ArrayList; 24 | import java.util.List; 25 | 26 | import org.bson.types.ObjectId; 27 | import org.openjdk.jmh.annotations.Benchmark; 28 | import org.openjdk.jmh.annotations.Scope; 29 | import org.openjdk.jmh.annotations.Setup; 30 | import org.openjdk.jmh.annotations.State; 31 | import org.openjdk.jmh.annotations.TearDown; 32 | 33 | import org.springframework.data.annotation.Id; 34 | import org.springframework.data.microbenchmark.common.AbstractMicrobenchmark; 35 | import org.springframework.data.mongodb.core.MongoTemplate; 36 | import org.springframework.data.mongodb.core.mapping.DBRef; 37 | import org.springframework.data.mongodb.core.query.Query; 38 | 39 | import com.mongodb.client.MongoClient; 40 | import com.mongodb.client.MongoClients; 41 | 42 | /** 43 | * @author Christoph Strobl 44 | */ 45 | @State(Scope.Benchmark) 46 | public class DbRefMappingBenchmark extends AbstractMicrobenchmark { 47 | 48 | private static final String DB_NAME = "dbref-loading-benchmark"; 49 | 50 | private MongoClient client; 51 | private MongoTemplate template; 52 | 53 | private Query queryObjectWithDBRef; 54 | private Query queryObjectWithDBRefList; 55 | 56 | @Setup 57 | public void setUp() throws Exception { 58 | 59 | client = MongoClients.create(); 60 | template = new MongoTemplate(client, DB_NAME); 61 | 62 | List refObjects = new ArrayList<>(); 63 | for (int i = 0; i < 1; i++) { 64 | RefObject o = new RefObject(); 65 | template.save(o); 66 | refObjects.add(o); 67 | } 68 | 69 | ObjectWithDBRef singleDBRef = new ObjectWithDBRef(); 70 | singleDBRef.ref = refObjects.iterator().next(); 71 | template.save(singleDBRef); 72 | 73 | ObjectWithDBRef multipleDBRefs = new ObjectWithDBRef(); 74 | multipleDBRefs.refList = refObjects; 75 | template.save(multipleDBRefs); 76 | 77 | queryObjectWithDBRef = query(where("id").is(singleDBRef.id)); 78 | queryObjectWithDBRefList = query(where("id").is(multipleDBRefs.id)); 79 | } 80 | 81 | @TearDown 82 | public void tearDown() { 83 | 84 | client.getDatabase(DB_NAME).drop(); 85 | client.close(); 86 | } 87 | 88 | @Benchmark // DATAMONGO-1720 89 | public ObjectWithDBRef readSingleDbRef() { 90 | return template.findOne(queryObjectWithDBRef, ObjectWithDBRef.class); 91 | } 92 | 93 | @Benchmark // DATAMONGO-1720 94 | public ObjectWithDBRef readMultipleDbRefs() { 95 | return template.findOne(queryObjectWithDBRefList, ObjectWithDBRef.class); 96 | } 97 | 98 | @Data 99 | static class ObjectWithDBRef { 100 | 101 | private @Id ObjectId id; 102 | private @DBRef RefObject ref; 103 | private @DBRef List refList; 104 | } 105 | 106 | @Data 107 | static class RefObject { 108 | 109 | private @Id String id; 110 | private String someValue; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/java/org/springframework/data/microbenchmark/jpa/JpaBenchmark.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.jpa; 17 | 18 | import java.util.Optional; 19 | 20 | import jakarta.persistence.EntityManager; 21 | import jakarta.persistence.Query; 22 | import jakarta.persistence.TypedQuery; 23 | import jakarta.persistence.criteria.CriteriaBuilder; 24 | import jakarta.persistence.criteria.CriteriaQuery; 25 | import jakarta.persistence.criteria.ParameterExpression; 26 | import jakarta.persistence.criteria.Root; 27 | 28 | import org.openjdk.jmh.annotations.Benchmark; 29 | import org.openjdk.jmh.annotations.Param; 30 | import org.openjdk.jmh.annotations.Setup; 31 | import org.openjdk.jmh.infra.Blackhole; 32 | import org.springframework.context.ConfigurableApplicationContext; 33 | import org.springframework.data.microbenchmark.common.AbstractMicrobenchmark; 34 | 35 | /** 36 | * Benchmarks for JPA and Spring Data JPA. 37 | * 38 | * @author Oliver Drotbohm 39 | */ 40 | public class JpaBenchmark extends AbstractMicrobenchmark { 41 | 42 | @Param({ "postgres", "h2-in-memory", "h2" }) 43 | String profile; 44 | 45 | EntityManager em; 46 | JpaBookRepository repository; 47 | 48 | @Setup 49 | public void setUp() { 50 | 51 | ConfigurableApplicationContext context = new JpaFixture(profile).getContext(); 52 | 53 | this.em = context.getBean(EntityManager.class); 54 | this.repository = context.getBean(JpaBookRepository.class); 55 | } 56 | 57 | @Benchmark 58 | public void findByTitle(Blackhole sink) { 59 | 60 | Query query = em.createQuery("select b from Book b where b.title = ?1"); 61 | query.setParameter(1, "title0"); 62 | 63 | sink.consume(query.getSingleResult()); 64 | } 65 | 66 | @Benchmark 67 | public void findByTitleCriteria(Blackhole sink) { 68 | 69 | CriteriaBuilder cb = em.getCriteriaBuilder(); 70 | CriteriaQuery q = cb.createQuery(Book.class); 71 | Root c = q.from(Book.class); 72 | 73 | ParameterExpression parameter = cb.parameter(String.class); 74 | 75 | TypedQuery query = em.createQuery(q.select(c).where(cb.equal(c.get("title"), parameter))); 76 | query.setParameter(parameter, "title0"); 77 | 78 | sink.consume(query.getSingleResult()); 79 | } 80 | 81 | @Benchmark 82 | public void findByTitleOptional(Blackhole sink) { 83 | 84 | Query query = em.createQuery("select b from Book b where b.title = ?1"); 85 | query.setParameter(1, "title0"); 86 | 87 | sink.consume(Optional.of(query.getSingleResult())); 88 | } 89 | 90 | @Benchmark 91 | public void findAll(Blackhole sink) { 92 | sink.consume(em.createQuery("select b from Book b").getResultList()); 93 | } 94 | 95 | @Benchmark 96 | public void repositoryFindByTitle(Blackhole sink) { 97 | sink.consume(repository.findDerivedByTitle("title0")); 98 | } 99 | 100 | @Benchmark 101 | public void repositoryFindTransactionalByTitle(Blackhole sink) { 102 | sink.consume(repository.findTransactionalDerivedByTitle("title0")); 103 | } 104 | 105 | @Benchmark 106 | public void repositoryFindByTitleDeclared(Blackhole sink) { 107 | sink.consume(repository.findDeclaredByTitle("title0")); 108 | } 109 | 110 | @Benchmark 111 | public void repositoryFindTransactionalByTitleDeclared(Blackhole sink) { 112 | sink.consume(repository.findTransactionalDeclaredByTitle("title0")); 113 | } 114 | 115 | @Benchmark 116 | public void repositoryFindByTitleOptional(Blackhole sink) { 117 | sink.consume(repository.findOptionalDerivedByTitle("title0")); 118 | } 119 | 120 | @Benchmark 121 | public void repositoryFindAll(Blackhole sink) { 122 | sink.consume(repository.findAll()); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /benchmark/support/src/main/java/org/springframework/data/microbenchmark/common/HttpResultsWriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.common; 17 | 18 | import jmh.mbr.core.ResultsWriter; 19 | import jmh.mbr.core.model.BenchmarkResults; 20 | import lombok.RequiredArgsConstructor; 21 | 22 | import java.io.ByteArrayOutputStream; 23 | import java.io.IOException; 24 | import java.io.OutputStream; 25 | import java.io.PrintStream; 26 | import java.net.HttpURLConnection; 27 | import java.net.URL; 28 | import java.net.URLConnection; 29 | import java.nio.charset.StandardCharsets; 30 | import java.time.Duration; 31 | import java.util.Collection; 32 | 33 | import lombok.SneakyThrows; 34 | import org.openjdk.jmh.results.RunResult; 35 | import org.openjdk.jmh.results.format.ResultFormatFactory; 36 | import org.openjdk.jmh.results.format.ResultFormatType; 37 | import org.openjdk.jmh.runner.format.OutputFormat; 38 | import org.springframework.core.env.StandardEnvironment; 39 | import org.springframework.util.CollectionUtils; 40 | 41 | /** 42 | * {@link ResultsWriterOld} implementation of {@link URLConnection}. 43 | * 44 | * @author Christoph Strobl 45 | * @author Mark Paluch 46 | */ 47 | @RequiredArgsConstructor 48 | class HttpResultsWriter implements ResultsWriter { 49 | 50 | private final String url; 51 | 52 | 53 | @Override 54 | public void write(OutputFormat output, BenchmarkResults benchmarkResults) { 55 | 56 | if (CollectionUtils.isEmpty(benchmarkResults.getRawResults())) { 57 | return; 58 | } 59 | 60 | try { 61 | doWrite(benchmarkResults.getRawResults()); 62 | } catch (IOException e) { 63 | output.println("Failed to write results: " + e); 64 | } 65 | } 66 | 67 | private void doWrite(Collection results) throws IOException { 68 | 69 | StandardEnvironment env = new StandardEnvironment(); 70 | 71 | String projectVersion = env.getProperty("project.version", "unknown"); 72 | String gitBranch = env.getProperty("git.branch", "unknown"); 73 | String gitDirty = env.getProperty("git.dirty", "no"); 74 | String gitCommitId = env.getProperty("git.commit.id", "unknown"); 75 | 76 | HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); 77 | connection.setConnectTimeout((int) Duration.ofSeconds(1).toMillis()); 78 | connection.setReadTimeout((int) Duration.ofSeconds(1).toMillis()); 79 | connection.setDoOutput(true); 80 | connection.setRequestMethod("POST"); 81 | 82 | connection.setRequestProperty("Content-Type", "application/json"); 83 | connection.addRequestProperty("X-Project-Version", projectVersion); 84 | connection.addRequestProperty("X-Git-Branch", gitBranch); 85 | connection.addRequestProperty("X-Git-Dirty", gitDirty); 86 | connection.addRequestProperty("X-Git-Commit-Id", gitCommitId); 87 | 88 | try (OutputStream output = connection.getOutputStream()) { 89 | output.write(jsonifyResults(results).getBytes(StandardCharsets.UTF_8)); 90 | } 91 | 92 | if (connection.getResponseCode() >= 400) { 93 | throw new IllegalStateException( 94 | String.format("Status %d %s", connection.getResponseCode(), connection.getResponseMessage())); 95 | } 96 | } 97 | 98 | /** 99 | * Convert {@link RunResult}s to JMH Json representation. 100 | * 101 | * @param results 102 | * @return json string representation of results. 103 | * @see org.openjdk.jmh.results.format.JSONResultFormat 104 | */ 105 | @SneakyThrows 106 | static String jsonifyResults(Collection results) { 107 | 108 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 109 | ResultFormatFactory.getInstance(ResultFormatType.JSON, new PrintStream(baos, true, "UTF-8")).writeOut(results); 110 | 111 | return new String(baos.toByteArray(), StandardCharsets.UTF_8); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /benchmark/mongodb/src/main/java/org/springframework/data/microbenchmark/mongodb/CallbacksBenchmark.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.mongodb; 17 | 18 | import org.bson.Document; 19 | import org.mockito.Mockito; 20 | import org.openjdk.jmh.annotations.Benchmark; 21 | import org.openjdk.jmh.annotations.Setup; 22 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 23 | import org.springframework.context.annotation.Bean; 24 | import org.springframework.context.annotation.Configuration; 25 | import org.springframework.data.microbenchmark.common.AbstractMicrobenchmark; 26 | import org.springframework.data.microbenchmark.mongodb.ProjectionsBenchmark.Address; 27 | import org.springframework.data.microbenchmark.mongodb.ProjectionsBenchmark.Person; 28 | import org.springframework.data.mongodb.MongoDatabaseFactory; 29 | import org.springframework.data.mongodb.core.MongoTemplate; 30 | import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory; 31 | import org.springframework.data.mongodb.core.mapping.event.BeforeConvertCallback; 32 | 33 | import com.mongodb.client.MongoClient; 34 | import com.mongodb.client.MongoCollection; 35 | import com.mongodb.client.MongoDatabase; 36 | 37 | /** 38 | * @author Christoph Strobl 39 | */ 40 | public class CallbacksBenchmark extends AbstractMicrobenchmark { 41 | 42 | private MongoTemplate templateWithoutContext; 43 | private MongoTemplate templateWithEmptyContext; 44 | private MongoTemplate templateWithContext; 45 | 46 | private Person source; 47 | 48 | @Setup 49 | public void setUp() { 50 | 51 | MongoClient client = Mockito.mock(MongoClient.class); 52 | MongoDatabase db = Mockito.mock(MongoDatabase.class); 53 | MongoCollection collection = Mockito.mock(MongoCollection.class); 54 | 55 | Mockito.when(client.getDatabase(Mockito.anyString())).thenReturn(db); 56 | Mockito.when(db.getCollection(Mockito.anyString(), Mockito.eq(Document.class))).thenReturn(collection); 57 | 58 | MongoDatabaseFactory factory = new SimpleMongoClientDatabaseFactory(client, "mock-database"); 59 | 60 | templateWithoutContext = new MongoTemplate(factory); 61 | 62 | templateWithEmptyContext = new MongoTemplate(factory); 63 | templateWithEmptyContext.setApplicationContext(new AnnotationConfigApplicationContext(EmptyConfig.class)); 64 | 65 | templateWithContext = new MongoTemplate(factory); 66 | templateWithContext.setApplicationContext(new AnnotationConfigApplicationContext(EntityCallbackConfig.class)); 67 | 68 | source = new Person(); 69 | source.id = "luke-skywalker"; 70 | source.firstname = "luke"; 71 | source.lastname = "skywalker"; 72 | 73 | source.address = new Address(); 74 | source.address.street = "melenium falcon 1"; 75 | source.address.city = "deathstar"; 76 | } 77 | 78 | @Benchmark 79 | public Object baseline() { 80 | return templateWithoutContext.save(source); 81 | } 82 | 83 | @Benchmark 84 | public Object emptyContext() { 85 | return templateWithEmptyContext.save(source); 86 | } 87 | 88 | @Benchmark 89 | public Object entityCallbacks() { 90 | return templateWithContext.save(source); 91 | } 92 | 93 | @Configuration 94 | static class EmptyConfig { 95 | 96 | } 97 | 98 | @Configuration 99 | static class EntityCallbackConfig { 100 | 101 | @Bean 102 | BeforeConvertCallback convertCallback() { 103 | return new PersonBeforeConvertCallback(); 104 | } 105 | 106 | private static class PersonBeforeConvertCallback implements BeforeConvertCallback { 107 | 108 | @Override 109 | public Person onBeforeConvert(Person it, String document) { 110 | 111 | Person target = new Person(); 112 | target.id = it.id; 113 | target.firstname = it.firstname = "luke"; 114 | target.lastname = it.lastname = "skywalker"; 115 | 116 | target.address = it.address; 117 | return target; 118 | } 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /benchmark/mongodb/src/main/java/org/springframework/data/microbenchmark/mongodb/MongoDbBenchmark.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.mongodb; 17 | 18 | import java.util.ArrayList; 19 | 20 | import org.bson.Document; 21 | import org.bson.conversions.Bson; 22 | import org.bson.types.ObjectId; 23 | import org.openjdk.jmh.annotations.Benchmark; 24 | import org.openjdk.jmh.annotations.Setup; 25 | import org.openjdk.jmh.infra.Blackhole; 26 | import org.springframework.context.ConfigurableApplicationContext; 27 | import org.springframework.data.microbenchmark.common.AbstractMicrobenchmark; 28 | import org.springframework.data.mongodb.core.ExecutableFindOperation.ExecutableFind; 29 | import org.springframework.data.mongodb.core.MongoOperations; 30 | import org.springframework.data.mongodb.core.convert.MappingMongoConverter; 31 | import org.springframework.data.mongodb.core.query.Criteria; 32 | import org.springframework.data.mongodb.core.query.Query; 33 | 34 | import com.mongodb.Function; 35 | import com.mongodb.client.MongoCollection; 36 | 37 | /** 38 | * @author Oliver Drotbohm 39 | */ 40 | public class MongoDbBenchmark extends AbstractMicrobenchmark { 41 | 42 | private static final Query BY_TITLE = Query.query(Criteria.where("title").is("title0")); 43 | 44 | private MongoCollection collection; 45 | private Function mapper; 46 | 47 | private ExecutableFind findBook; 48 | private MongoDbBookRepository repository; 49 | 50 | private MappingMongoConverter converter; 51 | private Bson bookSource; 52 | 53 | @Setup 54 | public void setUp() { 55 | 56 | ConfigurableApplicationContext context = new MongoDbFixture().getContext(); 57 | 58 | MongoOperations operations = context // 59 | .getBean(MongoOperations.class); 60 | 61 | this.collection = operations.getCollection(operations.getCollectionName(Book.class)); 62 | this.mapper = document -> new Book(document.getObjectId("_id"), document.getString("title"), document.getInteger("pages")); 63 | 64 | this.findBook = operations // 65 | .query(Book.class); 66 | 67 | this.repository = context // 68 | .getBean(MongoDbBookRepository.class); 69 | 70 | this.converter = context // 71 | .getBean(MappingMongoConverter.class); 72 | 73 | this.bookSource = new Document("title", "title1") // 74 | .append("pages", 42) // 75 | .append("_id", ObjectId.get()); 76 | } 77 | 78 | @Benchmark 79 | public void convertSingleBook(Blackhole sink) { 80 | sink.consume(converter.read(Book.class, bookSource)); 81 | } 82 | 83 | @Benchmark 84 | public void rawFindAll(Blackhole sink) { 85 | sink.consume(collection.find().map(mapper).into(new ArrayList<>())); 86 | } 87 | 88 | @Benchmark 89 | public void findAll(Blackhole sink) { 90 | sink.consume(findBook.all()); 91 | } 92 | 93 | @Benchmark 94 | public void repositoryFindAll(Blackhole sink) { 95 | sink.consume(repository.findAll()); 96 | } 97 | 98 | @Benchmark 99 | public void rawFindByTitle(Blackhole sink) { 100 | 101 | sink.consume(collection.find() // 102 | .filter(new Document("title", "title0")) // 103 | .map(mapper) // 104 | .first()); 105 | } 106 | 107 | @Benchmark 108 | public void findByTitle(Blackhole sink) { 109 | sink.consume(findBook.matching(BY_TITLE).firstValue()); 110 | } 111 | 112 | @Benchmark 113 | public void repositoryFindByTitle(Blackhole sink) { 114 | sink.consume(repository.findDerivedByTitle("title0")); 115 | } 116 | 117 | @Benchmark 118 | public void findByTitleOptional(Blackhole sink) { 119 | sink.consume(findBook.matching(BY_TITLE).first()); 120 | } 121 | 122 | @Benchmark 123 | public void repositoryFindByTitleOptional(Blackhole sink) { 124 | sink.consume(repository.findOptionalDerivedByTitle("title0")); 125 | } 126 | 127 | 128 | @Benchmark 129 | public void repositoryFindByTitleDeclared(Blackhole sink) { 130 | sink.consume(repository.findDeclaredByTitle("title0")); 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /benchmark/mongodb/src/main/java/org/springframework/data/microbenchmark/mongodb/AfterConvertCallbacksBenchmark.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.mongodb; 17 | 18 | import static org.mockito.Mockito.*; 19 | 20 | import org.bson.Document; 21 | import org.openjdk.jmh.annotations.Benchmark; 22 | import org.openjdk.jmh.annotations.Setup; 23 | 24 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 25 | import org.springframework.context.annotation.Bean; 26 | import org.springframework.context.annotation.Configuration; 27 | import org.springframework.context.support.StaticApplicationContext; 28 | import org.springframework.data.annotation.Id; 29 | import org.springframework.data.microbenchmark.common.AbstractMicrobenchmark; 30 | import org.springframework.data.mongodb.MongoDatabaseFactory; 31 | import org.springframework.data.mongodb.core.MongoTemplate; 32 | import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory; 33 | import org.springframework.data.mongodb.core.mapping.event.AfterConvertCallback; 34 | 35 | import com.mongodb.client.MongoClient; 36 | import com.mongodb.client.MongoCollection; 37 | import com.mongodb.client.MongoDatabase; 38 | 39 | /** 40 | * @author Roman Puchkovskiy 41 | */ 42 | public class AfterConvertCallbacksBenchmark extends AbstractMicrobenchmark { 43 | 44 | private MongoTemplate templateWithoutContext; 45 | private MongoTemplate templateWithEmptyContext; 46 | private MongoTemplate templateWithContext; 47 | 48 | private Person source; 49 | 50 | @Setup 51 | public void setUp() { 52 | 53 | MongoClient client = mock(MongoClient.class); 54 | MongoDatabase db = mock(MongoDatabase.class); 55 | MongoCollection collection = mock(MongoCollection.class); 56 | 57 | when(client.getDatabase(anyString())).thenReturn(db); 58 | when(db.getCollection(anyString(), eq(Document.class))).thenReturn(collection); 59 | 60 | MongoDatabaseFactory factory = new SimpleMongoClientDatabaseFactory(client, "mock-database"); 61 | 62 | templateWithoutContext = new MongoTemplate(factory); 63 | 64 | templateWithEmptyContext = new MongoTemplate(factory); 65 | StaticApplicationContext empty = new StaticApplicationContext(); 66 | empty.refresh(); 67 | templateWithEmptyContext.setApplicationContext(empty); 68 | 69 | templateWithContext = new MongoTemplate(factory); 70 | templateWithContext.setApplicationContext(new AnnotationConfigApplicationContext(EntityCallbackConfig.class)); 71 | 72 | source = new Person(); 73 | source.id = "luke-skywalker"; 74 | source.firstname = "luke"; 75 | source.lastname = "skywalker"; 76 | 77 | source.address = new Address(); 78 | source.address.street = "melenium falcon 1"; 79 | source.address.city = "deathstar"; 80 | } 81 | 82 | @Benchmark 83 | public Object baseline() { 84 | return templateWithoutContext.save(source); 85 | } 86 | 87 | @Benchmark 88 | public Object emptyContext() { 89 | return templateWithEmptyContext.save(source); 90 | } 91 | 92 | @Benchmark 93 | public Object entityCallbacks() { 94 | return templateWithContext.save(source); 95 | } 96 | 97 | @Configuration 98 | static class EntityCallbackConfig { 99 | 100 | @Bean 101 | AfterConvertCallback afterConvertCallback() { 102 | return new PersonAfterConvertCallback(); 103 | } 104 | 105 | private static class PersonAfterConvertCallback implements AfterConvertCallback { 106 | 107 | @Override 108 | public Person onAfterConvert(Person it, Document document, String collection) { 109 | 110 | Person target = new Person(); 111 | target.id = it.id; 112 | target.firstname = it.firstname = "luke"; 113 | target.lastname = it.lastname = "skywalker"; 114 | 115 | target.address = it.address; 116 | return target; 117 | } 118 | } 119 | } 120 | 121 | static class Person { 122 | 123 | @Id String id; 124 | String firstname; 125 | String lastname; 126 | Address address; 127 | } 128 | 129 | static class Address { 130 | 131 | String city; 132 | String street; 133 | } 134 | 135 | } 136 | -------------------------------------------------------------------------------- /benchmark/redis/src/main/java/org/springframework/data/microbenchmark/redis/ReactiveRedisTemplateBenchmark.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.redis; 17 | 18 | import io.lettuce.core.RedisClient; 19 | import io.lettuce.core.RedisURI; 20 | import io.lettuce.core.api.StatefulRedisConnection; 21 | import io.lettuce.core.resource.ClientResources; 22 | import io.lettuce.core.resource.DefaultClientResources; 23 | import reactor.core.publisher.Flux; 24 | 25 | import java.nio.ByteBuffer; 26 | import java.time.Duration; 27 | import java.util.concurrent.TimeUnit; 28 | 29 | import org.openjdk.jmh.annotations.Benchmark; 30 | import org.openjdk.jmh.annotations.OperationsPerInvocation; 31 | import org.openjdk.jmh.annotations.Setup; 32 | import org.openjdk.jmh.annotations.TearDown; 33 | 34 | import org.springframework.data.microbenchmark.common.AbstractMicrobenchmark; 35 | import org.springframework.data.redis.connection.ReactiveRedisConnection; 36 | import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; 37 | import org.springframework.data.redis.core.ReactiveRedisTemplate; 38 | import org.springframework.data.redis.serializer.RedisSerializationContext; 39 | 40 | /** 41 | * Benchmarks for {@link ReactiveRedisTemplate}. 42 | * 43 | * @author Mark Paluch 44 | */ 45 | public class ReactiveRedisTemplateBenchmark extends AbstractMicrobenchmark { 46 | 47 | private ClientResources clientResources; 48 | private ReactiveRedisTemplate template; 49 | private RedisClient client; 50 | private StatefulRedisConnection connection; 51 | 52 | @Setup 53 | public void setUp() { 54 | 55 | clientResources = DefaultClientResources.create(); 56 | 57 | LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(); 58 | connectionFactory.setClientResources(clientResources); 59 | connectionFactory.afterPropertiesSet(); 60 | 61 | ReactiveRedisConnection reactiveConnection = connectionFactory.getReactiveConnection(); 62 | reactiveConnection.keyCommands().del(ByteBuffer.wrap("user".getBytes())).block(); 63 | reactiveConnection.close(); 64 | 65 | client = RedisClient.create(clientResources, RedisURI.create("localhost", 6379)); 66 | connection = client.connect(); 67 | template = new ReactiveRedisTemplate<>(connectionFactory, RedisSerializationContext.string()); 68 | } 69 | 70 | @TearDown 71 | public void tearDown() { 72 | connection.close(); 73 | client.shutdown(Duration.ZERO, Duration.ZERO); 74 | clientResources.shutdown(0, 0, TimeUnit.MILLISECONDS); 75 | } 76 | 77 | @Benchmark 78 | public void clientOnly() { 79 | connection.sync().incr("user"); 80 | } 81 | 82 | @Benchmark 83 | @OperationsPerInvocation(1000) 84 | public long clientReactiveConcatMap() { 85 | return Flux.range(0, 1000).concatMap(it -> connection.reactive().incr("user")).blockLast(); 86 | } 87 | 88 | @Benchmark 89 | @OperationsPerInvocation(1000) 90 | public long clientReactiveFlatMap() { 91 | return Flux.range(0, 1000).flatMap(it -> connection.reactive().incr("user")).blockLast(); 92 | } 93 | 94 | @Benchmark 95 | @OperationsPerInvocation(1000) 96 | public long templateReactiveConcatMap() { 97 | return Flux.range(0, 1000).concatMap(it -> template.opsForValue().increment("user")).blockLast(); 98 | } 99 | 100 | @Benchmark 101 | @OperationsPerInvocation(1000) 102 | public long templateReactiveFlatMap() { 103 | return Flux.range(0, 1000).flatMap(it -> template.opsForValue().increment("user")).blockLast(); 104 | } 105 | 106 | /* 107 | @Benchmark 108 | @OperationsPerInvocation(1000) 109 | public long templateReactiveExecuteInSessionConcatMap() { 110 | return template 111 | .executeInSession(session -> Flux.range(0, 1000).concatMap(i -> session.opsForValue().increment("user"))) 112 | .blockLast(); 113 | } 114 | 115 | @Benchmark 116 | @OperationsPerInvocation(1000) 117 | public long templateReactiveExecuteInSessionFlatMap() { 118 | return template 119 | .executeInSession(session -> Flux.range(0, 1000).flatMap(i -> session.opsForValue().increment("user"))) 120 | .blockLast(); 121 | } */ 122 | 123 | } 124 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/java/org/springframework/data/microbenchmark/jdbc/JdbcBenchmark.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.jdbc; 17 | 18 | import java.util.HashMap; 19 | import java.util.Set; 20 | import java.util.TreeSet; 21 | 22 | import org.openjdk.jmh.annotations.Benchmark; 23 | import org.openjdk.jmh.annotations.Param; 24 | import org.openjdk.jmh.annotations.Setup; 25 | import org.openjdk.jmh.infra.Blackhole; 26 | import org.openjdk.jmh.util.Optional; 27 | import org.springframework.context.ConfigurableApplicationContext; 28 | import org.springframework.data.jdbc.core.convert.EntityRowMapper; 29 | import org.springframework.data.jdbc.core.convert.JdbcConverter; 30 | import org.springframework.data.jdbc.core.mapping.JdbcMappingContext; 31 | import org.springframework.data.microbenchmark.common.AbstractMicrobenchmark; 32 | import org.springframework.data.relational.core.mapping.RelationalPersistentEntity; 33 | import org.springframework.jdbc.core.JdbcOperations; 34 | import org.springframework.jdbc.core.RowMapper; 35 | 36 | import com.mockrunner.mock.jdbc.MockResultSet; 37 | 38 | /** 39 | * Benchmark for JDBC and Spring Data JDBC 40 | * 41 | * @author Oliver Drotbohm 42 | */ 43 | public class JdbcBenchmark extends AbstractMicrobenchmark { 44 | 45 | private static final String BY_TITLE_SQL = "SELECT id, title, pages FROM Book where title = ?"; 46 | 47 | @Param({ /*"postgres",*/ "h2-in-memory", /*"h2"*/ }) String profile; 48 | 49 | JdbcOperations operations; 50 | RowMapper bookMapper; 51 | EntityRowMapper bookEntityMapper; 52 | JdbcBookRepository repository; 53 | 54 | Set columns; 55 | HashMap values; 56 | @Setup 57 | @SuppressWarnings("unchecked") 58 | public void setUp() { 59 | 60 | JdbcFixture fixture = new JdbcFixture(profile); 61 | 62 | this.bookMapper = fixture.getBookMapper(); 63 | 64 | ConfigurableApplicationContext context = fixture.getContext(); 65 | 66 | this.operations = context.getBean(JdbcOperations.class); 67 | this.repository = context.getBean(JdbcBookRepository.class); 68 | 69 | JdbcConverter converter = context.getBean(JdbcConverter.class); 70 | JdbcMappingContext mappingContext = context.getBean(JdbcMappingContext.class); 71 | 72 | RelationalPersistentEntity requiredPersistentEntity = (RelationalPersistentEntity) mappingContext 73 | .getRequiredPersistentEntity(Book.class); 74 | 75 | this.bookEntityMapper = new EntityRowMapper(requiredPersistentEntity, converter); 76 | 77 | // ResultSet mock 78 | 79 | this.columns = new TreeSet<>(); 80 | columns.add("id"); 81 | columns.add("title"); 82 | columns.add("pages"); 83 | 84 | this.values = new HashMap<>(); 85 | values.put("id", 1L); 86 | values.put("title", "title0"); 87 | values.put("pages", 42L); 88 | } 89 | 90 | @Benchmark 91 | public void convertWithSpringData(Blackhole sink) throws Exception { 92 | 93 | MockResultSet resultSet = new MockResultSet("book"); 94 | resultSet.addColumns(columns); 95 | resultSet.addRow(values); 96 | resultSet.next(); 97 | 98 | sink.consume(this.bookEntityMapper.mapRow(resultSet, 1)); 99 | } 100 | 101 | @Benchmark 102 | public void findByTitle(Blackhole sink) { 103 | sink.consume(operations.queryForObject(BY_TITLE_SQL, new Object[] { "title0" }, bookMapper)); 104 | } 105 | 106 | @Benchmark 107 | public void findByTitleOptional(Blackhole sink) { 108 | sink.consume(Optional.of(operations.queryForObject(BY_TITLE_SQL, new Object[] { "title0" }, bookMapper))); 109 | } 110 | 111 | @Benchmark 112 | public void findAll(Blackhole sink) { 113 | sink.consume(operations.query("SELECT id, title, pages FROM Book", bookMapper)); 114 | } 115 | 116 | @Benchmark 117 | public void findAllWithSpringDataConversion(Blackhole sink) { 118 | sink.consume(operations.query("SELECT id, title, pages FROM Book", bookEntityMapper)); 119 | } 120 | 121 | @Benchmark 122 | public void repositoryFindByTitle(Blackhole sink) { 123 | sink.consume(repository.findByTitle("title0")); 124 | } 125 | 126 | @Benchmark 127 | public void repositoryFindTransactionalByTitle(Blackhole sink) { 128 | sink.consume(repository.findTransactionalByTitle("title0")); 129 | } 130 | 131 | @Benchmark 132 | public void repositoryFindByTitleOptional(Blackhole sink) { 133 | sink.consume(repository.findOptionalByTitle("title0")); 134 | } 135 | 136 | @Benchmark 137 | public void repositoryFindAll(Blackhole sink) { 138 | sink.consume(repository.findAll()); 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /benchmark/relational/src/main/java/org/springframework/data/microbenchmark/jdbc/JdbcFixture.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.jdbc; 17 | 18 | import lombok.Getter; 19 | 20 | import java.lang.reflect.Field; 21 | 22 | import org.h2.jdbcx.JdbcDataSource; 23 | import org.postgresql.ds.PGSimpleDataSource; 24 | import org.springframework.aop.framework.Advised; 25 | import org.springframework.boot.autoconfigure.SpringBootApplication; 26 | import org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration; 27 | import org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration; 28 | import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; 29 | import org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration; 30 | import org.springframework.boot.autoconfigure.r2dbc.R2dbcTransactionManagerAutoConfiguration; 31 | import org.springframework.boot.context.properties.ConfigurationProperties; 32 | import org.springframework.context.ApplicationContext; 33 | import org.springframework.context.ApplicationEventPublisher; 34 | import org.springframework.context.ConfigurableApplicationContext; 35 | import org.springframework.context.annotation.Bean; 36 | import org.springframework.context.annotation.Configuration; 37 | import org.springframework.context.annotation.Profile; 38 | import org.springframework.data.jdbc.core.JdbcAggregateTemplate; 39 | import org.springframework.data.jdbc.repository.support.SimpleJdbcRepository; 40 | import org.springframework.data.mapping.callback.EntityCallback; 41 | import org.springframework.data.mapping.callback.EntityCallbacks; 42 | import org.springframework.data.microbenchmark.FixtureUtils; 43 | import org.springframework.jdbc.core.RowMapper; 44 | import org.springframework.util.ReflectionUtils; 45 | 46 | import javax.sql.DataSource; 47 | 48 | /** 49 | * Test fixture for JDBC and Spring Data JDBC benchmarks. 50 | * 51 | * @author Oliver Drotbohm 52 | */ 53 | class JdbcFixture { 54 | 55 | private final @Getter ConfigurableApplicationContext context; 56 | private final @Getter RowMapper bookMapper; 57 | 58 | JdbcFixture(String database) { 59 | 60 | this.context = FixtureUtils.createContext(JdbcApplication.class, "jdbc", database); 61 | 62 | // disableEntityCallbacks(context); 63 | 64 | this.bookMapper = (rs, rowNum) -> new Book(rs.getLong("id"), rs.getString("title"), rs.getInt("pages")); 65 | } 66 | 67 | private static void disableEntityCallbacks(ApplicationContext context) { 68 | 69 | JdbcBookRepository repository = context.getBean(JdbcBookRepository.class); 70 | 71 | Field field = ReflectionUtils.findField(SimpleJdbcRepository.class, "entityOperations"); 72 | ReflectionUtils.makeAccessible(field); 73 | 74 | try { 75 | JdbcAggregateTemplate aggregateTemplate = (JdbcAggregateTemplate) ReflectionUtils.getField(field, 76 | ((Advised) repository).getTargetSource().getTarget()); 77 | 78 | field = ReflectionUtils.findField(JdbcAggregateTemplate.class, "publisher"); 79 | ReflectionUtils.makeAccessible(field); 80 | ReflectionUtils.setField(field, aggregateTemplate, NoOpApplicationEventPublisher.INSTANCE); 81 | 82 | aggregateTemplate.setEntityCallbacks(NoOpEntityCallbacks.INSTANCE); 83 | 84 | } catch (Exception o_O) { 85 | throw new RuntimeException(o_O); 86 | } 87 | } 88 | 89 | @SpringBootApplication( 90 | exclude = { 91 | R2dbcAutoConfiguration.class, 92 | R2dbcDataAutoConfiguration.class, 93 | R2dbcRepositoriesAutoConfiguration.class, 94 | R2dbcTransactionManagerAutoConfiguration.class, 95 | HibernateJpaAutoConfiguration.class 96 | } 97 | ) 98 | static class JdbcApplication { 99 | 100 | @Bean 101 | @Profile({"h2","h2-in-memory"}) 102 | @ConfigurationProperties(prefix = "spring.datasource") 103 | DataSource dataSourceH2() { 104 | return new JdbcDataSource(); 105 | } 106 | 107 | @Bean 108 | @Profile({"postgres"}) 109 | @ConfigurationProperties(prefix = "spring.datasource") 110 | DataSource dataSourcePostgres() { 111 | PGSimpleDataSource dataSource = new PGSimpleDataSource(); 112 | return dataSource; 113 | } 114 | 115 | } 116 | 117 | 118 | 119 | enum NoOpApplicationEventPublisher implements ApplicationEventPublisher { 120 | 121 | INSTANCE; 122 | 123 | @Override 124 | public void publishEvent(Object event) {} 125 | } 126 | 127 | enum NoOpEntityCallbacks implements EntityCallbacks { 128 | 129 | INSTANCE; 130 | 131 | @Override 132 | public void addEntityCallback(EntityCallback callback) {} 133 | 134 | @Override 135 | @SuppressWarnings("rawtypes") 136 | public T callback(Class callbackType, T entity, Object... args) { 137 | return entity; 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /benchmark/support/src/main/java/org/springframework/data/microbenchmark/common/MongoResultsWriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.common; 17 | 18 | import jmh.mbr.core.ResultsWriter; 19 | import jmh.mbr.core.model.BenchmarkResults; 20 | import lombok.RequiredArgsConstructor; 21 | import net.minidev.json.JSONArray; 22 | import net.minidev.json.JSONObject; 23 | import net.minidev.json.parser.JSONParser; 24 | import net.minidev.json.parser.ParseException; 25 | 26 | import java.util.Collection; 27 | import java.util.Date; 28 | import java.util.Map; 29 | 30 | import org.bson.Document; 31 | import org.openjdk.jmh.results.RunResult; 32 | import org.openjdk.jmh.runner.format.OutputFormat; 33 | import org.springframework.core.env.StandardEnvironment; 34 | import org.springframework.util.CollectionUtils; 35 | import org.springframework.util.ObjectUtils; 36 | import org.springframework.util.StringUtils; 37 | 38 | import com.mongodb.ConnectionString; 39 | import com.mongodb.client.MongoClient; 40 | import com.mongodb.client.MongoClients; 41 | import com.mongodb.client.MongoDatabase; 42 | 43 | /** 44 | * MongoDB specific {@link ResultsWriter} implementation. 45 | * 46 | * @author Christoph Strobl 47 | * @author Mark Paluch 48 | * @author Roman Puchkovskiy 49 | */ 50 | @RequiredArgsConstructor 51 | class MongoResultsWriter implements ResultsWriter { 52 | 53 | private final String uri; 54 | 55 | @Override 56 | public void write(OutputFormat output, BenchmarkResults benchmarkResults) { 57 | 58 | if (CollectionUtils.isEmpty(benchmarkResults.getRawResults())) { 59 | return; 60 | } 61 | 62 | try { 63 | doWrite(benchmarkResults.getRawResults()); 64 | } catch (ParseException | RuntimeException e) { 65 | output.println("Failed to write results: " + e.toString()); 66 | } 67 | } 68 | 69 | private void doWrite(Collection results) throws ParseException { 70 | 71 | Date now = new Date(); 72 | StandardEnvironment env = new StandardEnvironment(); 73 | 74 | String projectVersion = env.getProperty("project.version", "unknown"); 75 | String gitBranch = env.getProperty("git.branch", "unknown"); 76 | String gitDirty = env.getProperty("git.dirty", "no"); 77 | String gitCommitId = env.getProperty("git.commit.id", "unknown"); 78 | 79 | ConnectionString uri = new ConnectionString(this.uri); 80 | MongoClient client = MongoClients.create(); 81 | 82 | String dbName = StringUtils.hasText(uri.getDatabase()) ? uri.getDatabase() : "spring-data-mongodb-benchmarks"; 83 | MongoDatabase db = client.getDatabase(dbName); 84 | 85 | String resultsJson = HttpResultsWriter.jsonifyResults(results).trim(); 86 | JSONArray array = (JSONArray) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(resultsJson); 87 | for (Object object : array) { 88 | JSONObject dbo = (JSONObject) object; 89 | 90 | String collectionName = extractClass(dbo.get("benchmark").toString()); 91 | 92 | Document sink = new Document(); 93 | sink.append("_version", projectVersion); 94 | sink.append("_branch", gitBranch); 95 | sink.append("_commit", gitCommitId); 96 | sink.append("_dirty", gitDirty); 97 | sink.append("_method", extractBenchmarkName(dbo.get("benchmark").toString())); 98 | sink.append("_date", now); 99 | sink.append("_snapshot", projectVersion.toLowerCase().contains("snapshot")); 100 | 101 | sink.putAll(dbo); 102 | 103 | db.getCollection(collectionName).insertOne(fixDocumentKeys(sink)); 104 | } 105 | 106 | client.close(); 107 | } 108 | 109 | /** 110 | * Replace {@code .} by {@code ,}. 111 | * 112 | * @param doc 113 | * @return 114 | */ 115 | private static Document fixDocumentKeys(Document doc) { 116 | 117 | Document sanitized = new Document(); 118 | 119 | for (Object key : doc.keySet()) { 120 | 121 | Object value = doc.get(key); 122 | if (value instanceof Document) { 123 | value = fixDocumentKeys((Document) value); 124 | } else if (value instanceof Map) { 125 | value = fixDocumentKeys(new Document((Map) value)); 126 | } 127 | 128 | if (key instanceof String) { 129 | 130 | String newKey = (String) key; 131 | if (newKey.contains(".")) { 132 | newKey = newKey.replace('.', ','); 133 | } 134 | 135 | sanitized.put(newKey, value); 136 | } else { 137 | sanitized.put(ObjectUtils.nullSafeToString(key).replace('.', ','), value); 138 | } 139 | } 140 | 141 | return sanitized; 142 | } 143 | 144 | private static String extractClass(String source) { 145 | 146 | String tmp = source.substring(0, source.lastIndexOf('.')); 147 | return tmp.substring(tmp.lastIndexOf(".") + 1); 148 | } 149 | 150 | private static String extractBenchmarkName(String source) { 151 | return source.substring(source.lastIndexOf(".") + 1); 152 | } 153 | 154 | } 155 | -------------------------------------------------------------------------------- /benchmark/mongodb/src/main/java/org/springframework/data/microbenchmark/mongodb/ProjectionsBenchmark.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.mongodb; 17 | 18 | import org.bson.Document; 19 | import org.openjdk.jmh.annotations.Benchmark; 20 | import org.openjdk.jmh.annotations.Setup; 21 | import org.openjdk.jmh.annotations.TearDown; 22 | import org.springframework.beans.factory.annotation.Value; 23 | import org.springframework.data.annotation.Id; 24 | import org.springframework.data.microbenchmark.common.AbstractMicrobenchmark; 25 | import org.springframework.data.mongodb.core.ExecutableFindOperation.FindWithQuery; 26 | import org.springframework.data.mongodb.core.ExecutableFindOperation.TerminatingFind; 27 | import org.springframework.data.mongodb.core.MongoTemplate; 28 | import org.springframework.data.mongodb.core.mapping.Field; 29 | import org.springframework.data.mongodb.core.query.BasicQuery; 30 | 31 | import com.mongodb.client.MongoClient; 32 | import com.mongodb.client.MongoClients; 33 | import com.mongodb.client.MongoCollection; 34 | 35 | /** 36 | * @author Christoph Strobl 37 | */ 38 | public class ProjectionsBenchmark extends AbstractMicrobenchmark { 39 | 40 | private static final String DB_NAME = "projections-benchmark"; 41 | private static final String COLLECTION_NAME = "projections"; 42 | 43 | private MongoTemplate template; 44 | private MongoClient client; 45 | private MongoCollection mongoCollection; 46 | 47 | private Person source; 48 | 49 | private FindWithQuery asPerson; 50 | private FindWithQuery asDtoProjection; 51 | private FindWithQuery asClosedProjection; 52 | private FindWithQuery asOpenProjection; 53 | 54 | private TerminatingFind asPersonWithFieldsRestriction; 55 | private Document fields = new Document("firstname", 1); 56 | 57 | @Setup 58 | public void setUp() { 59 | 60 | client = MongoClients.create(); 61 | template = new MongoTemplate(client, DB_NAME); 62 | 63 | source = new Person(); 64 | source.firstname = "luke"; 65 | source.lastname = "skywalker"; 66 | 67 | source.address = new Address(); 68 | source.address.street = "melenium falcon 1"; 69 | source.address.city = "deathstar"; 70 | 71 | template.save(source, COLLECTION_NAME); 72 | 73 | asPerson = template.query(Person.class).inCollection(COLLECTION_NAME); 74 | asDtoProjection = template.query(Person.class).inCollection(COLLECTION_NAME).as(DtoProjection.class); 75 | asClosedProjection = template.query(Person.class).inCollection(COLLECTION_NAME).as(ClosedProjection.class); 76 | asOpenProjection = template.query(Person.class).inCollection(COLLECTION_NAME).as(OpenProjection.class); 77 | 78 | asPersonWithFieldsRestriction = template.query(Person.class).inCollection(COLLECTION_NAME) 79 | .matching(new BasicQuery(new Document(), fields)); 80 | 81 | mongoCollection = client.getDatabase(DB_NAME).getCollection(COLLECTION_NAME); 82 | } 83 | 84 | @TearDown 85 | public void tearDown() { 86 | 87 | client.getDatabase(DB_NAME).drop(); 88 | client.close(); 89 | } 90 | 91 | /** 92 | * Set the baseline for comparison by using the plain MongoDB java driver api without any additional fluff. 93 | * 94 | * @return 95 | */ 96 | @Benchmark // DATAMONGO-1733 97 | public Object baseline() { 98 | return mongoCollection.find().first(); 99 | } 100 | 101 | /** 102 | * Read into the domain type including all fields. 103 | * 104 | * @return 105 | */ 106 | @Benchmark // DATAMONGO-1733 107 | public Object readIntoDomainType() { 108 | return asPerson.all(); 109 | } 110 | 111 | /** 112 | * Read into the domain type but restrict query to only return one field. 113 | * 114 | * @return 115 | */ 116 | @Benchmark // DATAMONGO-1733 117 | public Object readIntoDomainTypeRestrictingToOneField() { 118 | return asPersonWithFieldsRestriction.all(); 119 | } 120 | 121 | /** 122 | * Read into dto projection that only needs to map one field back. 123 | * 124 | * @return 125 | */ 126 | @Benchmark // DATAMONGO-1733 127 | public Object readIntoDtoProjectionWithOneField() { 128 | return asDtoProjection.all(); 129 | } 130 | 131 | /** 132 | * Read into closed interface projection. 133 | * 134 | * @return 135 | */ 136 | @Benchmark // DATAMONGO-1733 137 | public Object readIntoClosedProjectionWithOneField() { 138 | return asClosedProjection.all(); 139 | } 140 | 141 | /** 142 | * Read into an open projection backed by the mapped domain object. 143 | * 144 | * @return 145 | */ 146 | @Benchmark // DATAMONGO-1733 147 | public Object readIntoOpenProjection() { 148 | return asOpenProjection.all(); 149 | } 150 | 151 | static class Person { 152 | 153 | @Id String id; 154 | String firstname; 155 | String lastname; 156 | Address address; 157 | } 158 | 159 | static class Address { 160 | 161 | String city; 162 | String street; 163 | } 164 | 165 | static class DtoProjection { 166 | 167 | @Field("firstname") String name; 168 | } 169 | 170 | static interface ClosedProjection { 171 | 172 | String getFirstname(); 173 | } 174 | 175 | static interface OpenProjection { 176 | 177 | @Value("#{target.firstname}") 178 | String name(); 179 | } 180 | 181 | } 182 | -------------------------------------------------------------------------------- /benchmark/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 4.0.0 7 | 8 | org.springframework.data.benchmark 9 | spring-data-benchmark-parent 10 | pom 11 | 12 | Spring Data Benchmarks 13 | JMH Benchmarks for Spring Data 14 | 15 | 16 | org.springframework.data.build 17 | spring-data-parent 18 | 3.3.0-SNAPSHOT 19 | 20 | 21 | 22 | 23 | support 24 | commons 25 | mongodb 26 | redis 27 | relational 28 | 29 | 30 | 31 | 1.37 32 | 33 | 34 | 35 | 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-dependencies 40 | 3.3.0-SNAPSHOT 41 | pom 42 | import 43 | 44 | 45 | 46 | org.springframework.data 47 | spring-data-bom 48 | 2024.0.0-SNAPSHOT 49 | pom 50 | import 51 | 52 | 53 | 54 | ${project.groupId} 55 | spring-data-benchmark-support 56 | ${project.version} 57 | 58 | 59 | 60 | com.github.mp911de.microbenchmark-runner 61 | microbenchmark-runner-junit4 62 | 0.4.0.RELEASE 63 | 64 | 65 | 66 | com.github.mp911de.microbenchmark-runner 67 | microbenchmark-runner-extras 68 | 0.4.0.RELEASE 69 | 70 | 71 | 72 | net.minidev 73 | json-smart 74 | 2.5.0 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | org.springframework 83 | spring-core 84 | 85 | 86 | 87 | junit 88 | junit 89 | ${junit} 90 | compile 91 | 92 | 93 | 94 | org.openjdk.jmh 95 | jmh-core 96 | ${jmh.version} 97 | 98 | 99 | 100 | org.openjdk.jmh 101 | jmh-generator-annprocess 102 | ${jmh.version} 103 | provided 104 | 105 | 106 | 107 | org.projectlombok 108 | lombok 109 | provided 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | org.apache.maven.plugins 118 | maven-compiler-plugin 119 | 3.10.1 120 | 121 | 17 122 | 17 123 | true 124 | 125 | 126 | 127 | pl.project13.maven 128 | git-commit-id-plugin 129 | 2.2.2 130 | 131 | 132 | 133 | revision 134 | 135 | 136 | 137 | 138 | 139 | maven-surefire-plugin 140 | 141 | ${project.build.sourceDirectory} 142 | 143 | ${project.build.outputDirectory} 144 | 145 | 146 | **/AbstractMicrobenchmark.java 147 | **/*$*.class 148 | **/generated/*.class 149 | 150 | 151 | **/*Benchmark* 152 | 153 | 154 | 155 | ${project.build.directory}/reports/performance 156 | 157 | ${project.version} 158 | ${git.dirty} 159 | ${git.commit.id} 160 | ${git.branch} 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | spring-snapshot 170 | https://repo.spring.io/snapshot 171 | 172 | 173 | 174 | spring-milestone 175 | https://repo.spring.io/milestone 176 | 177 | 178 | 179 | jitpack.io 180 | https://jitpack.io 181 | 182 | 183 | 184 | 185 | 186 | spring-plugins-release 187 | https://repo.spring.io/plugins-release 188 | 189 | 190 | spring-libs-milestone 191 | https://repo.spring.io/libs-milestone 192 | 193 | 194 | 195 | 196 | -------------------------------------------------------------------------------- /benchmark/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Apache Maven Wrapper startup batch script, version 3.2.0 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 28 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 29 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 30 | @REM e.g. to debug Maven itself, use 31 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 32 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 33 | @REM ---------------------------------------------------------------------------- 34 | 35 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 36 | @echo off 37 | @REM set title of command window 38 | title %0 39 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 40 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 41 | 42 | @REM set %HOME% to equivalent of $HOME 43 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 44 | 45 | @REM Execute a user defined script before this one 46 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 47 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 48 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* 49 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* 50 | :skipRcPre 51 | 52 | @setlocal 53 | 54 | set ERROR_CODE=0 55 | 56 | @REM To isolate internal variables from possible post scripts, we use another setlocal 57 | @setlocal 58 | 59 | @REM ==== START VALIDATION ==== 60 | if not "%JAVA_HOME%" == "" goto OkJHome 61 | 62 | echo. 63 | echo Error: JAVA_HOME not found in your environment. >&2 64 | echo Please set the JAVA_HOME variable in your environment to match the >&2 65 | echo location of your Java installation. >&2 66 | echo. 67 | goto error 68 | 69 | :OkJHome 70 | if exist "%JAVA_HOME%\bin\java.exe" goto init 71 | 72 | echo. 73 | echo Error: JAVA_HOME is set to an invalid directory. >&2 74 | echo JAVA_HOME = "%JAVA_HOME%" >&2 75 | echo Please set the JAVA_HOME variable in your environment to match the >&2 76 | echo location of your Java installation. >&2 77 | echo. 78 | goto error 79 | 80 | @REM ==== END VALIDATION ==== 81 | 82 | :init 83 | 84 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 85 | @REM Fallback to current working directory if not found. 86 | 87 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 88 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 89 | 90 | set EXEC_DIR=%CD% 91 | set WDIR=%EXEC_DIR% 92 | :findBaseDir 93 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 94 | cd .. 95 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 96 | set WDIR=%CD% 97 | goto findBaseDir 98 | 99 | :baseDirFound 100 | set MAVEN_PROJECTBASEDIR=%WDIR% 101 | cd "%EXEC_DIR%" 102 | goto endDetectBaseDir 103 | 104 | :baseDirNotFound 105 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 106 | cd "%EXEC_DIR%" 107 | 108 | :endDetectBaseDir 109 | 110 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 111 | 112 | @setlocal EnableExtensions EnableDelayedExpansion 113 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 114 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 115 | 116 | :endReadAdditionalConfig 117 | 118 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" 123 | 124 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 125 | IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B 126 | ) 127 | 128 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 129 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 130 | if exist %WRAPPER_JAR% ( 131 | if "%MVNW_VERBOSE%" == "true" ( 132 | echo Found %WRAPPER_JAR% 133 | ) 134 | ) else ( 135 | if not "%MVNW_REPOURL%" == "" ( 136 | SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" 137 | ) 138 | if "%MVNW_VERBOSE%" == "true" ( 139 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 140 | echo Downloading from: %WRAPPER_URL% 141 | ) 142 | 143 | powershell -Command "&{"^ 144 | "$webclient = new-object System.Net.WebClient;"^ 145 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 146 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 147 | "}"^ 148 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ 149 | "}" 150 | if "%MVNW_VERBOSE%" == "true" ( 151 | echo Finished downloading %WRAPPER_JAR% 152 | ) 153 | ) 154 | @REM End of extension 155 | 156 | @REM If specified, validate the SHA-256 sum of the Maven wrapper jar file 157 | SET WRAPPER_SHA_256_SUM="" 158 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 159 | IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B 160 | ) 161 | IF NOT %WRAPPER_SHA_256_SUM%=="" ( 162 | powershell -Command "&{"^ 163 | "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ 164 | "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ 165 | " Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ 166 | " Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ 167 | " Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ 168 | " exit 1;"^ 169 | "}"^ 170 | "}" 171 | if ERRORLEVEL 1 goto error 172 | ) 173 | 174 | @REM Provide a "standardized" way to retrieve the CLI args that will 175 | @REM work with both Windows and non-Windows executions. 176 | set MAVEN_CMD_LINE_ARGS=%* 177 | 178 | %MAVEN_JAVA_EXE% ^ 179 | %JVM_CONFIG_MAVEN_PROPS% ^ 180 | %MAVEN_OPTS% ^ 181 | %MAVEN_DEBUG_OPTS% ^ 182 | -classpath %WRAPPER_JAR% ^ 183 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ 184 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 185 | if ERRORLEVEL 1 goto error 186 | goto end 187 | 188 | :error 189 | set ERROR_CODE=1 190 | 191 | :end 192 | @endlocal & set ERROR_CODE=%ERROR_CODE% 193 | 194 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost 195 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 196 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" 197 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" 198 | :skipRcPost 199 | 200 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 201 | if "%MAVEN_BATCH_PAUSE%"=="on" pause 202 | 203 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% 204 | 205 | cmd /C exit /B %ERROR_CODE% 206 | -------------------------------------------------------------------------------- /benchmark/mongodb/src/main/java/org/springframework/data/microbenchmark/mongodb/convert/MappingMongoConverterBenchmark.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.mongodb.convert; 17 | 18 | import lombok.AllArgsConstructor; 19 | import lombok.Data; 20 | import lombok.Getter; 21 | import lombok.RequiredArgsConstructor; 22 | 23 | import java.util.Arrays; 24 | import java.util.Collections; 25 | import java.util.LinkedHashMap; 26 | import java.util.List; 27 | import java.util.Map; 28 | import java.util.UUID; 29 | 30 | import org.bson.Document; 31 | import org.bson.types.ObjectId; 32 | import org.openjdk.jmh.annotations.Benchmark; 33 | import org.openjdk.jmh.annotations.Scope; 34 | import org.openjdk.jmh.annotations.Setup; 35 | import org.openjdk.jmh.annotations.State; 36 | import org.openjdk.jmh.annotations.TearDown; 37 | 38 | import org.springframework.data.annotation.Id; 39 | import org.springframework.data.geo.Point; 40 | import org.springframework.data.microbenchmark.common.AbstractMicrobenchmark; 41 | import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory; 42 | import org.springframework.data.mongodb.core.convert.DbRefResolver; 43 | import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver; 44 | import org.springframework.data.mongodb.core.convert.MappingMongoConverter; 45 | import org.springframework.data.mongodb.core.convert.MongoCustomConversions; 46 | import org.springframework.data.mongodb.core.mapping.Field; 47 | import org.springframework.data.mongodb.core.mapping.MongoMappingContext; 48 | 49 | import com.mongodb.client.MongoClient; 50 | import com.mongodb.client.MongoClients; 51 | 52 | /** 53 | * @author Christoph Strobl 54 | */ 55 | @State(Scope.Benchmark) 56 | public class MappingMongoConverterBenchmark extends AbstractMicrobenchmark { 57 | 58 | private static final String DB_NAME = "mapping-mongo-converter-benchmark"; 59 | 60 | private MongoClient client; 61 | private MongoMappingContext mappingContext; 62 | private MappingMongoConverter converter; 63 | private Document documentWith2Properties, documentWith2PropertiesAnd1Nested; 64 | private Customer objectWith2PropertiesAnd1Nested; 65 | 66 | private Document documentWithFlatAndComplexPropertiesPlusListAndMap; 67 | private SlightlyMoreComplexObject objectWithFlatAndComplexPropertiesPlusListAndMap; 68 | 69 | @Setup 70 | public void setUp() throws Exception { 71 | 72 | client = MongoClients.create(); 73 | 74 | this.mappingContext = new MongoMappingContext(); 75 | this.mappingContext.setInitialEntitySet(Collections.singleton(Customer.class)); 76 | this.mappingContext.afterPropertiesSet(); 77 | 78 | DbRefResolver dbRefResolver = new DefaultDbRefResolver(new SimpleMongoClientDatabaseFactory(client, DB_NAME)); 79 | 80 | this.converter = new MappingMongoConverter(dbRefResolver, mappingContext); 81 | this.converter.setCustomConversions(new MongoCustomConversions(Collections.emptyList())); 82 | this.converter.afterPropertiesSet(); 83 | 84 | // just a flat document 85 | this.documentWith2Properties = new Document("firstname", "Dave").append("lastname", "Matthews"); 86 | 87 | // document with a nested one 88 | Document address = new Document("zipCode", "ABCDE").append("city", "Some Place"); 89 | this.documentWith2PropertiesAnd1Nested = new Document("firstname", "Dave").// 90 | append("lastname", "Matthews").// 91 | append("address", address); 92 | 93 | // object equivalent of documentWith2PropertiesAnd1Nested 94 | this.objectWith2PropertiesAnd1Nested = new Customer("Dave", "Matthews", new Address("zipCode", "City")); 95 | 96 | // a bit more challenging object with list & map conversion. 97 | objectWithFlatAndComplexPropertiesPlusListAndMap = new SlightlyMoreComplexObject(); 98 | objectWithFlatAndComplexPropertiesPlusListAndMap.id = UUID.randomUUID().toString(); 99 | objectWithFlatAndComplexPropertiesPlusListAndMap.addressList = Arrays.asList(new Address("zip-1", "city-1"), 100 | new Address("zip-2", "city-2")); 101 | objectWithFlatAndComplexPropertiesPlusListAndMap.customer = objectWith2PropertiesAnd1Nested; 102 | objectWithFlatAndComplexPropertiesPlusListAndMap.customerMap = new LinkedHashMap<>(); 103 | objectWithFlatAndComplexPropertiesPlusListAndMap.customerMap.put("dave", objectWith2PropertiesAnd1Nested); 104 | objectWithFlatAndComplexPropertiesPlusListAndMap.customerMap.put("deborah", 105 | new Customer("Deborah Anne", "Dyer", new Address("?", "london"))); 106 | objectWithFlatAndComplexPropertiesPlusListAndMap.customerMap.put("eddie", 107 | new Customer("Eddie", "Vedder", new Address("??", "Seattle"))); 108 | objectWithFlatAndComplexPropertiesPlusListAndMap.intOne = Integer.MIN_VALUE; 109 | objectWithFlatAndComplexPropertiesPlusListAndMap.intTwo = Integer.MAX_VALUE; 110 | objectWithFlatAndComplexPropertiesPlusListAndMap.location = new Point(-33.865143, 151.209900); 111 | objectWithFlatAndComplexPropertiesPlusListAndMap.renamedField = "supercalifragilisticexpialidocious"; 112 | objectWithFlatAndComplexPropertiesPlusListAndMap.stringOne = "¯\\_(ツ)_/¯"; 113 | objectWithFlatAndComplexPropertiesPlusListAndMap.stringTwo = " (╯°□°)╯︵ ┻━┻"; 114 | 115 | // JSON equivalent of objectWithFlatAndComplexPropertiesPlusListAndMap 116 | documentWithFlatAndComplexPropertiesPlusListAndMap = Document.parse( 117 | "{ \"_id\" : \"517f6aee-e9e0-44f0-88ed-f3694a019f27\", \"intOne\" : -2147483648, \"intTwo\" : 2147483647, \"stringOne\" : \"¯\\\\_(ツ)_/¯\", \"stringTwo\" : \" (╯°□°)╯︵ ┻━┻\", \"explicit-field-name\" : \"supercalifragilisticexpialidocious\", \"location\" : { \"x\" : -33.865143, \"y\" : 151.2099 }, \"objectWith2PropertiesAnd1Nested\" : { \"firstname\" : \"Dave\", \"lastname\" : \"Matthews\", \"address\" : { \"zipCode\" : \"zipCode\", \"city\" : \"City\" } }, \"addressList\" : [{ \"zipCode\" : \"zip-1\", \"city\" : \"city-1\" }, { \"zipCode\" : \"zip-2\", \"city\" : \"city-2\" }], \"customerMap\" : { \"dave\" : { \"firstname\" : \"Dave\", \"lastname\" : \"Matthews\", \"address\" : { \"zipCode\" : \"zipCode\", \"city\" : \"City\" } }, \"deborah\" : { \"firstname\" : \"Deborah Anne\", \"lastname\" : \"Dyer\", \"address\" : { \"zipCode\" : \"?\", \"city\" : \"london\" } }, \"eddie\" : { \"firstname\" : \"Eddie\", \"lastname\" : \"Vedder\", \"address\" : { \"zipCode\" : \"??\", \"city\" : \"Seattle\" } } }, \"_class\" : \"org.springframework.data.mongodb.core.convert.MappingMongoConverterBenchmark$SlightlyMoreComplexObject\" }"); 118 | 119 | } 120 | 121 | @TearDown 122 | public void tearDown() { 123 | 124 | client.getDatabase(DB_NAME).drop(); 125 | client.close(); 126 | } 127 | 128 | @Benchmark // DATAMONGO-1720 129 | public Customer readObjectWith2Properties() { 130 | return converter.read(Customer.class, documentWith2Properties); 131 | } 132 | 133 | @Benchmark // DATAMONGO-1720 134 | public Customer readObjectWith2PropertiesAnd1NestedObject() { 135 | return converter.read(Customer.class, documentWith2PropertiesAnd1Nested); 136 | } 137 | 138 | @Benchmark // DATAMONGO-1720 139 | public Document writeObjectWith2PropertiesAnd1NestedObject() { 140 | 141 | Document sink = new Document(); 142 | converter.write(objectWith2PropertiesAnd1Nested, sink); 143 | return sink; 144 | } 145 | 146 | @Benchmark // DATAMONGO-1720 147 | public Object readObjectWithListAndMapsOfComplexType() { 148 | return converter.read(SlightlyMoreComplexObject.class, documentWithFlatAndComplexPropertiesPlusListAndMap); 149 | } 150 | 151 | @Benchmark // DATAMONGO-1720 152 | public Object writeObjectWithListAndMapsOfComplexType() { 153 | 154 | Document sink = new Document(); 155 | converter.write(objectWithFlatAndComplexPropertiesPlusListAndMap, sink); 156 | return sink; 157 | } 158 | 159 | @Getter 160 | @RequiredArgsConstructor 161 | public static class Customer { 162 | 163 | private @Id ObjectId id; 164 | private final String firstname, lastname; 165 | private final Address address; 166 | } 167 | 168 | @Getter 169 | @AllArgsConstructor 170 | public static class Address { 171 | private String zipCode, city; 172 | } 173 | 174 | @Data 175 | public static class SlightlyMoreComplexObject { 176 | 177 | @Id String id; 178 | int intOne, intTwo; 179 | String stringOne, stringTwo; 180 | @Field("explicit-field-name") String renamedField; 181 | Point location; 182 | Customer customer; 183 | List
addressList; 184 | Map customerMap; 185 | } 186 | 187 | } 188 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | https://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | https://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /benchmark/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Apache Maven Wrapper startup batch script, version 3.2.0 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | # e.g. to debug Maven itself, use 32 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | # ---------------------------------------------------------------------------- 35 | 36 | if [ -z "$MAVEN_SKIP_RC" ] ; then 37 | 38 | if [ -f /usr/local/etc/mavenrc ] ; then 39 | . /usr/local/etc/mavenrc 40 | fi 41 | 42 | if [ -f /etc/mavenrc ] ; then 43 | . /etc/mavenrc 44 | fi 45 | 46 | if [ -f "$HOME/.mavenrc" ] ; then 47 | . "$HOME/.mavenrc" 48 | fi 49 | 50 | fi 51 | 52 | # OS specific support. $var _must_ be set to either true or false. 53 | cygwin=false; 54 | darwin=false; 55 | mingw=false 56 | case "$(uname)" in 57 | CYGWIN*) cygwin=true ;; 58 | MINGW*) mingw=true;; 59 | Darwin*) darwin=true 60 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 61 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 62 | if [ -z "$JAVA_HOME" ]; then 63 | if [ -x "/usr/libexec/java_home" ]; then 64 | JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME 65 | else 66 | JAVA_HOME="/Library/Java/Home"; export JAVA_HOME 67 | fi 68 | fi 69 | ;; 70 | esac 71 | 72 | if [ -z "$JAVA_HOME" ] ; then 73 | if [ -r /etc/gentoo-release ] ; then 74 | JAVA_HOME=$(java-config --jre-home) 75 | fi 76 | fi 77 | 78 | # For Cygwin, ensure paths are in UNIX format before anything is touched 79 | if $cygwin ; then 80 | [ -n "$JAVA_HOME" ] && 81 | JAVA_HOME=$(cygpath --unix "$JAVA_HOME") 82 | [ -n "$CLASSPATH" ] && 83 | CLASSPATH=$(cygpath --path --unix "$CLASSPATH") 84 | fi 85 | 86 | # For Mingw, ensure paths are in UNIX format before anything is touched 87 | if $mingw ; then 88 | [ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] && 89 | JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)" 90 | fi 91 | 92 | if [ -z "$JAVA_HOME" ]; then 93 | javaExecutable="$(which javac)" 94 | if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then 95 | # readlink(1) is not available as standard on Solaris 10. 96 | readLink=$(which readlink) 97 | if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then 98 | if $darwin ; then 99 | javaHome="$(dirname "\"$javaExecutable\"")" 100 | javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac" 101 | else 102 | javaExecutable="$(readlink -f "\"$javaExecutable\"")" 103 | fi 104 | javaHome="$(dirname "\"$javaExecutable\"")" 105 | javaHome=$(expr "$javaHome" : '\(.*\)/bin') 106 | JAVA_HOME="$javaHome" 107 | export JAVA_HOME 108 | fi 109 | fi 110 | fi 111 | 112 | if [ -z "$JAVACMD" ] ; then 113 | if [ -n "$JAVA_HOME" ] ; then 114 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 115 | # IBM's JDK on AIX uses strange locations for the executables 116 | JAVACMD="$JAVA_HOME/jre/sh/java" 117 | else 118 | JAVACMD="$JAVA_HOME/bin/java" 119 | fi 120 | else 121 | JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)" 122 | fi 123 | fi 124 | 125 | if [ ! -x "$JAVACMD" ] ; then 126 | echo "Error: JAVA_HOME is not defined correctly." >&2 127 | echo " We cannot execute $JAVACMD" >&2 128 | exit 1 129 | fi 130 | 131 | if [ -z "$JAVA_HOME" ] ; then 132 | echo "Warning: JAVA_HOME environment variable is not set." 133 | fi 134 | 135 | # traverses directory structure from process work directory to filesystem root 136 | # first directory with .mvn subdirectory is considered project base directory 137 | find_maven_basedir() { 138 | if [ -z "$1" ] 139 | then 140 | echo "Path not specified to find_maven_basedir" 141 | return 1 142 | fi 143 | 144 | basedir="$1" 145 | wdir="$1" 146 | while [ "$wdir" != '/' ] ; do 147 | if [ -d "$wdir"/.mvn ] ; then 148 | basedir=$wdir 149 | break 150 | fi 151 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 152 | if [ -d "${wdir}" ]; then 153 | wdir=$(cd "$wdir/.." || exit 1; pwd) 154 | fi 155 | # end of workaround 156 | done 157 | printf '%s' "$(cd "$basedir" || exit 1; pwd)" 158 | } 159 | 160 | # concatenates all lines of a file 161 | concat_lines() { 162 | if [ -f "$1" ]; then 163 | # Remove \r in case we run on Windows within Git Bash 164 | # and check out the repository with auto CRLF management 165 | # enabled. Otherwise, we may read lines that are delimited with 166 | # \r\n and produce $'-Xarg\r' rather than -Xarg due to word 167 | # splitting rules. 168 | tr -s '\r\n' ' ' < "$1" 169 | fi 170 | } 171 | 172 | log() { 173 | if [ "$MVNW_VERBOSE" = true ]; then 174 | printf '%s\n' "$1" 175 | fi 176 | } 177 | 178 | BASE_DIR=$(find_maven_basedir "$(dirname "$0")") 179 | if [ -z "$BASE_DIR" ]; then 180 | exit 1; 181 | fi 182 | 183 | MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR 184 | log "$MAVEN_PROJECTBASEDIR" 185 | 186 | ########################################################################################## 187 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 188 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 189 | ########################################################################################## 190 | wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" 191 | if [ -r "$wrapperJarPath" ]; then 192 | log "Found $wrapperJarPath" 193 | else 194 | log "Couldn't find $wrapperJarPath, downloading it ..." 195 | 196 | if [ -n "$MVNW_REPOURL" ]; then 197 | wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" 198 | else 199 | wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" 200 | fi 201 | while IFS="=" read -r key value; do 202 | # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' ) 203 | safeValue=$(echo "$value" | tr -d '\r') 204 | case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;; 205 | esac 206 | done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" 207 | log "Downloading from: $wrapperUrl" 208 | 209 | if $cygwin; then 210 | wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") 211 | fi 212 | 213 | if command -v wget > /dev/null; then 214 | log "Found wget ... using wget" 215 | [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" 216 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 217 | wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 218 | else 219 | wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 220 | fi 221 | elif command -v curl > /dev/null; then 222 | log "Found curl ... using curl" 223 | [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" 224 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 225 | curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" 226 | else 227 | curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" 228 | fi 229 | else 230 | log "Falling back to using Java to download" 231 | javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" 232 | javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" 233 | # For Cygwin, switch paths to Windows format before running javac 234 | if $cygwin; then 235 | javaSource=$(cygpath --path --windows "$javaSource") 236 | javaClass=$(cygpath --path --windows "$javaClass") 237 | fi 238 | if [ -e "$javaSource" ]; then 239 | if [ ! -e "$javaClass" ]; then 240 | log " - Compiling MavenWrapperDownloader.java ..." 241 | ("$JAVA_HOME/bin/javac" "$javaSource") 242 | fi 243 | if [ -e "$javaClass" ]; then 244 | log " - Running MavenWrapperDownloader.java ..." 245 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" 246 | fi 247 | fi 248 | fi 249 | fi 250 | ########################################################################################## 251 | # End of extension 252 | ########################################################################################## 253 | 254 | # If specified, validate the SHA-256 sum of the Maven wrapper jar file 255 | wrapperSha256Sum="" 256 | while IFS="=" read -r key value; do 257 | case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;; 258 | esac 259 | done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" 260 | if [ -n "$wrapperSha256Sum" ]; then 261 | wrapperSha256Result=false 262 | if command -v sha256sum > /dev/null; then 263 | if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then 264 | wrapperSha256Result=true 265 | fi 266 | elif command -v shasum > /dev/null; then 267 | if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then 268 | wrapperSha256Result=true 269 | fi 270 | else 271 | echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." 272 | echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." 273 | exit 1 274 | fi 275 | if [ $wrapperSha256Result = false ]; then 276 | echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 277 | echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 278 | echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 279 | exit 1 280 | fi 281 | fi 282 | 283 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 284 | 285 | # For Cygwin, switch paths to Windows format before running java 286 | if $cygwin; then 287 | [ -n "$JAVA_HOME" ] && 288 | JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") 289 | [ -n "$CLASSPATH" ] && 290 | CLASSPATH=$(cygpath --path --windows "$CLASSPATH") 291 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 292 | MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") 293 | fi 294 | 295 | # Provide a "standardized" way to retrieve the CLI args that will 296 | # work with both Windows and non-Windows executions. 297 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*" 298 | export MAVEN_CMD_LINE_ARGS 299 | 300 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 301 | 302 | # shellcheck disable=SC2086 # safe args 303 | exec "$JAVACMD" \ 304 | $MAVEN_OPTS \ 305 | $MAVEN_DEBUG_OPTS \ 306 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 307 | "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 308 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 309 | -------------------------------------------------------------------------------- /benchmark/commons/src/main/java/org/springframework/data/microbenchmark/commons/convert/TypicalEntityReaderBenchmark.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2022 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.springframework.data.microbenchmark.commons.convert; 17 | 18 | import lombok.Data; 19 | import lombok.RequiredArgsConstructor; 20 | 21 | import java.util.Collections; 22 | import java.util.HashMap; 23 | import java.util.Map; 24 | 25 | import org.openjdk.jmh.annotations.Benchmark; 26 | import org.springframework.core.convert.ConversionService; 27 | import org.springframework.core.convert.support.DefaultConversionService; 28 | import org.springframework.data.annotation.AccessType; 29 | import org.springframework.data.annotation.AccessType.Type; 30 | import org.springframework.data.convert.CustomConversions; 31 | import org.springframework.data.convert.CustomConversions.StoreConversions; 32 | import org.springframework.data.mapping.Association; 33 | import org.springframework.data.mapping.Parameter; 34 | import org.springframework.data.mapping.PersistentEntity; 35 | import org.springframework.data.mapping.PersistentProperty; 36 | import org.springframework.data.mapping.PersistentPropertyAccessor; 37 | import org.springframework.data.mapping.PreferredConstructor; 38 | import org.springframework.data.mapping.context.AbstractMappingContext; 39 | import org.springframework.data.mapping.context.MappingContext; 40 | import org.springframework.data.mapping.model.AnnotationBasedPersistentProperty; 41 | import org.springframework.data.mapping.model.BasicPersistentEntity; 42 | import org.springframework.data.mapping.model.ConvertingPropertyAccessor; 43 | import org.springframework.data.mapping.model.EntityInstantiator; 44 | import org.springframework.data.mapping.model.EntityInstantiators; 45 | import org.springframework.data.mapping.model.ParameterValueProvider; 46 | import org.springframework.data.mapping.model.Property; 47 | import org.springframework.data.mapping.model.PropertyValueProvider; 48 | import org.springframework.data.mapping.model.SimpleTypeHolder; 49 | import org.springframework.data.microbenchmark.common.AbstractMicrobenchmark; 50 | import org.springframework.data.util.TypeInformation; 51 | 52 | /** 53 | * Benchmark for a typical converter that reads entities. 54 | * 55 | * @author Mark Paluch 56 | */ 57 | public class TypicalEntityReaderBenchmark extends AbstractMicrobenchmark { 58 | 59 | private final MyMappingContext context = new MyMappingContext(); 60 | private final EntityInstantiators instantiators = new EntityInstantiators(); 61 | private final ConversionService conversionService = DefaultConversionService.getSharedInstance(); 62 | private final CustomConversions customConversions = new CustomConversions(StoreConversions.NONE, 63 | Collections.emptyList()); 64 | private final ParameterValueProvider NONE = new ParameterValueProvider() { 65 | 66 | @Override 67 | public T getParameterValue(Parameter parameter) { 68 | return null; 69 | } 70 | }; 71 | 72 | private final Map simpleEntityData = new HashMap<>(); 73 | 74 | /** 75 | * Prepare and pre-initialize to remove initialization overhead from measurement. 76 | */ 77 | public TypicalEntityReaderBenchmark() { 78 | 79 | instantiators.getInstantiatorFor(context.getRequiredPersistentEntity(SimpleEntity.class)); 80 | instantiators.getInstantiatorFor(context.getRequiredPersistentEntity(SimpleAccessibleEntityPropertyAccess.class)); 81 | instantiators.getInstantiatorFor(context.getRequiredPersistentEntity(SimpleAccessibleEntityFieldAccess.class)); 82 | instantiators.getInstantiatorFor(context.getRequiredPersistentEntity(SimpleEntityWithConstructor.class)); 83 | 84 | instantiators.getInstantiatorFor(context.getRequiredPersistentEntity(MyDataClass.class)); 85 | instantiators.getInstantiatorFor(context.getRequiredPersistentEntity(MyDataClassWithDefaulting.class)); 86 | 87 | simpleEntityData.put("firstname", "Walter"); 88 | simpleEntityData.put("lastname", "White"); 89 | } 90 | 91 | @Benchmark 92 | public Object simpleEntityReflectiveFieldAccess() { 93 | return read(simpleEntityData, SimpleEntity.class, false); 94 | } 95 | 96 | @Benchmark 97 | public Object simpleEntityReflectivePropertyAccess() { 98 | return read(simpleEntityData, SimpleEntityPropertyAccess.class, false); 99 | } 100 | 101 | @Benchmark 102 | public Object simpleEntityReflectivePropertyAccessWithCustomConversionRegistry() { 103 | return read(simpleEntityData, SimpleEntity.class, true); 104 | } 105 | 106 | @Benchmark 107 | public Object simpleEntityGeneratedPropertyAccess() { 108 | return read(simpleEntityData, SimpleAccessibleEntityPropertyAccess.class, false); 109 | } 110 | 111 | @Benchmark 112 | public Object simpleEntityGeneratedFieldAccess() { 113 | return read(simpleEntityData, SimpleAccessibleEntityFieldAccess.class, false); 114 | } 115 | 116 | @Benchmark 117 | public Object simpleEntityGeneratedConstructorArgsCreation() { 118 | return read(simpleEntityData, SimpleEntityWithConstructor.class, false); 119 | } 120 | 121 | @Benchmark 122 | public Object simpleEntityReflectiveConstructorArgsCreation() { 123 | return read(simpleEntityData, SimpleEntityWithReflectiveConstructor.class, false); 124 | } 125 | 126 | @Benchmark 127 | public Object simpleEntityReflectiveConstructorAndProperty() { 128 | return read(simpleEntityData, SimpleEntityWithConstructorAndProperty.class, false); 129 | } 130 | 131 | @Benchmark 132 | public Object simpleEntityReflectiveConstructorAndField() { 133 | return read(simpleEntityData, SimpleEntityWithConstructorAndField.class, false); 134 | } 135 | 136 | @Benchmark 137 | public Object simpleEntityGeneratedConstructorAndProperty() { 138 | return read(simpleEntityData, SimpleEntityWithGeneratedConstructorAndProperty.class, false); 139 | } 140 | 141 | @Benchmark 142 | public Object simpleEntityGeneratedConstructorAndField() { 143 | return read(simpleEntityData, SimpleEntityWithGeneratedConstructorAndField.class, false); 144 | } 145 | 146 | @Benchmark 147 | public Object kotlinDataClass() { 148 | return read(simpleEntityData, MyDataClass.class, false); 149 | } 150 | 151 | @Benchmark 152 | public Object kotlinDataClassWithDefaulting() { 153 | return read(simpleEntityData, MyDataClassWithDefaulting.class, false); 154 | } 155 | 156 | @Benchmark 157 | public boolean hasReadTarget() { 158 | return customConversions.hasCustomReadTarget(String.class, Object.class); 159 | } 160 | 161 | static class SimpleEntity { 162 | String firstname, lastname; 163 | } 164 | 165 | @Data 166 | @AccessType(Type.PROPERTY) 167 | private static class SimpleEntityPropertyAccess { 168 | String firstname, lastname; 169 | } 170 | 171 | @Data 172 | @AccessType(Type.PROPERTY) 173 | public static class SimpleAccessibleEntityPropertyAccess { 174 | String firstname, lastname; 175 | } 176 | 177 | @Data 178 | public static class SimpleAccessibleEntityFieldAccess { 179 | public String firstname, lastname; 180 | } 181 | 182 | @RequiredArgsConstructor 183 | public static class SimpleEntityWithConstructor { 184 | final String firstname, lastname; 185 | } 186 | 187 | @RequiredArgsConstructor 188 | private static class SimpleEntityWithReflectiveConstructor { 189 | final String firstname, lastname; 190 | } 191 | 192 | @Data 193 | @RequiredArgsConstructor 194 | private static class SimpleEntityWithConstructorAndField { 195 | 196 | final String firstname; 197 | String lastname; 198 | } 199 | 200 | @Data 201 | @AccessType(Type.PROPERTY) 202 | @RequiredArgsConstructor 203 | private static class SimpleEntityWithConstructorAndProperty { 204 | 205 | final String firstname; 206 | String lastname; 207 | } 208 | 209 | @Data 210 | @AccessType(Type.PROPERTY) 211 | @RequiredArgsConstructor 212 | public static class SimpleEntityWithGeneratedConstructorAndProperty { 213 | 214 | final String firstname; 215 | String lastname; 216 | } 217 | 218 | @Data 219 | @RequiredArgsConstructor 220 | public static class SimpleEntityWithGeneratedConstructorAndField { 221 | 222 | final String firstname; 223 | String lastname; 224 | } 225 | 226 | /** 227 | * Typical code used to read entities in {@link org.springframework.data.convert.EntityReader}. 228 | * 229 | * @param data 230 | * @param classToRead 231 | * @param queryCustomConversions {@literal true} to call {@link CustomConversions#hasCustomReadTarget(Class, Class)}. 232 | * @return 233 | */ 234 | @SuppressWarnings("unchecked") 235 | private Object read(Map data, Class classToRead, boolean queryCustomConversions) { 236 | 237 | if (queryCustomConversions) { 238 | customConversions.hasCustomReadTarget(Map.class, classToRead); 239 | } 240 | 241 | MyPersistentEntity persistentEntity = context.getRequiredPersistentEntity(classToRead); 242 | PreferredConstructor constructor = persistentEntity.getPersistenceConstructor(); 243 | 244 | ParameterValueProvider provider = constructor.isNoArgConstructor() // 245 | ? NONE // 246 | : new ParameterValueProvider() { 247 | 248 | @Override 249 | public T getParameterValue(Parameter parameter) { 250 | return (T) getValue(data, parameter.getName(), parameter.getType().getType(), queryCustomConversions); 251 | } 252 | }; 253 | 254 | EntityInstantiator instantiator = instantiators.getInstantiatorFor(persistentEntity); 255 | Object instance = instantiator.createInstance(persistentEntity, provider); 256 | 257 | if (!persistentEntity.requiresPropertyPopulation()) { 258 | return instance; 259 | } 260 | 261 | PropertyValueProvider valueProvider = new PropertyValueProvider() { 262 | 263 | @Override 264 | public T getPropertyValue(MyPersistentProperty property) { 265 | return (T) getValue(data, property.getName(), property.getType(), queryCustomConversions); 266 | } 267 | }; 268 | 269 | PersistentPropertyAccessor accessor = new ConvertingPropertyAccessor<>( 270 | persistentEntity.getPropertyAccessor(instance), conversionService); 271 | 272 | readProperties(data, persistentEntity, valueProvider, accessor); 273 | 274 | return accessor.getBean(); 275 | } 276 | 277 | private void readProperties(Map data, MyPersistentEntity persistentEntity, 278 | PropertyValueProvider valueProvider, PersistentPropertyAccessor accessor) { 279 | 280 | for (MyPersistentProperty prop : persistentEntity) { 281 | 282 | if (prop.isAssociation() && !persistentEntity.isConstructorArgument(prop)) { 283 | continue; 284 | } 285 | 286 | // We skip the id property since it was already set 287 | 288 | if (persistentEntity.isIdProperty(prop)) { 289 | continue; 290 | } 291 | 292 | if (persistentEntity.isConstructorArgument(prop) || !data.containsKey(persistentEntity.getName())) { 293 | continue; 294 | } 295 | 296 | accessor.setProperty(prop, valueProvider.getPropertyValue(prop)); 297 | } 298 | } 299 | 300 | private Object getValue(Map data, String name, Class type, boolean queryCustomConversions) { 301 | 302 | Object value = data.get(name); 303 | 304 | if (queryCustomConversions && value != null) { 305 | customConversions.hasCustomReadTarget(value.getClass(), type); 306 | } 307 | 308 | return value; 309 | } 310 | 311 | /** 312 | * Minimal {@link MappingContext}. 313 | */ 314 | static class MyMappingContext extends AbstractMappingContext, MyPersistentProperty> { 315 | 316 | /* 317 | * (non-Javadoc) 318 | * @see org.springframework.data.mapping.context.AbstractMappingContext#createPersistentEntity(org.springframework.data.util.TypeInformation) 319 | */ 320 | @Override 321 | protected MyPersistentEntity createPersistentEntity(TypeInformation typeInformation) { 322 | return new MyPersistentEntity(typeInformation); 323 | } 324 | 325 | /* 326 | * (non-Javadoc) 327 | * @see org.springframework.data.mapping.context.AbstractMappingContext#createPersistentProperty(org.springframework.data.mapping.model.Property, org.springframework.data.mapping.model.MutablePersistentEntity, org.springframework.data.mapping.model.SimpleTypeHolder) 328 | */ 329 | @Override 330 | protected MyPersistentProperty createPersistentProperty(Property property, MyPersistentEntity owner, 331 | SimpleTypeHolder simpleTypeHolder) { 332 | return new MyPersistentProperty(property, owner, simpleTypeHolder); 333 | } 334 | } 335 | 336 | /** 337 | * Minimal {@link PersistentProperty}. 338 | */ 339 | static class MyPersistentProperty extends AnnotationBasedPersistentProperty { 340 | 341 | MyPersistentProperty(Property property, PersistentEntity owner, 342 | SimpleTypeHolder simpleTypeHolder) { 343 | super(property, owner, simpleTypeHolder); 344 | } 345 | 346 | /* 347 | * (non-Javadoc) 348 | * @see org.springframework.data.mapping.model.AbstractPersistentProperty#createAssociation() 349 | */ 350 | @Override 351 | protected Association createAssociation() { 352 | return null; 353 | } 354 | } 355 | 356 | /** 357 | * Minimal {@link PersistentEntity}. 358 | * 359 | * @param 360 | */ 361 | static class MyPersistentEntity extends BasicPersistentEntity { 362 | 363 | MyPersistentEntity(TypeInformation information) { 364 | super(information); 365 | } 366 | } 367 | } 368 | --------------------------------------------------------------------------------