Compare commits

...

1039 Commits

Author SHA1 Message Date
Christoph Strobl
d94d273010 Fix test 2023-01-25 15:05:56 +01:00
Christoph Strobl
b9f6463337 decrypt? 2023-01-25 14:32:38 +01:00
Christoph Strobl
095022e71d reactive FLE encryptiion works -> next decrypt 2023-01-25 14:32:35 +01:00
Christoph Strobl
329b4b2881 Hacking - Reactive FLE
experiment with resolving reactive types in document
2023-01-25 14:24:35 +01:00
Christoph Strobl
73aeb7a425 Test encryption during update 2023-01-25 14:24:35 +01:00
Christoph Strobl
4b8ac4d249 Some changes that allow reading the alt key from a field
typically only supported in automatic schema but neat to have it here as well. eg. for customer data cyper based on eg. username.
Also make sure to translate decryption exceptions.
2023-01-25 14:24:35 +01:00
Christoph Strobl
1a7157fa7c Encrypt collection of complex types. 2023-01-25 14:24:35 +01:00
Christoph Strobl
10a089fe77 Encrypt collection of simple values 2023-01-25 14:24:35 +01:00
Christoph Strobl
7b93379165 Enable full encryption of nested documents. 2023-01-25 14:24:35 +01:00
Christoph Strobl
0361c3acc9 Hacking 2023-01-25 14:24:35 +01:00
Christoph Strobl
a6641e0c01 Prepare issue branch. 2023-01-25 14:24:34 +01:00
Mark Paluch
33902b5061 Polishing.
Move QuerydslPredicateExecutor hints to RepositoryRuntimeHints.

See #4244
Original pull request: #4245
2023-01-23 14:08:43 +01:00
Christoph Strobl
d00db4bd40 Add missing hints for Querydsl integration.
This commit adds missing reflection configuration for Querydsl integration. We now also make sure to call the queryMixing getter instead of reading the field via reflection.

Closes #4244
Original pull request: #4245
2023-01-23 14:08:43 +01:00
Christoph Strobl
a5dcbf043a Update links in reference documentation.
We now use the springDocsUrl attribute provided via spring-projects/spring-data-build#1895 to resolve links to framework documentation.

Original Pull Request: #4267
2023-01-18 14:23:22 +01:00
robeatoz
c31203582f Fix parameter and method name in reference documentation.
Closes: #4247
2023-01-16 11:22:29 +01:00
Emre Uygun
f146afecdc Fix typo in reference documentation.
Closes: #4250
2023-01-16 11:19:32 +01:00
Christoph Strobl
324a541a64 Polishing.
Original Pull Request: #4255
2023-01-16 11:17:49 +01:00
Michael Krog
6b71d773d7 Fixes return in Javadoc.
Closes: #4255
2023-01-16 11:15:14 +01:00
Patouche
10447afe0c Fix typo in reference documentation.
Closes: #4268
2023-01-16 10:49:42 +01:00
soumyaPrakashB
c9dfd60f0f Add missing Nullable annotation.
For one of constructor arguments of the AggregationOptions the Nullable annotation for the cursor argument is missing.

Closes: #4256
2023-01-16 10:47:28 +01:00
Mark Paluch
26a8fafd03 Upgrade to MongoDB driver 4.8.2.
Closes #4270
2023-01-13 10:30:01 +01:00
Mark Paluch
00f652a094 Polishing.
Add missing package-info.

See #4248
Original pull request: #4249
2023-01-12 08:47:16 +01:00
Christoph Strobl
d050ae5732 Exclude mongodb and data.mongodb namespaces from reflection contribution.
In some cases the users domain model may hold references to spring data or MongoDB specific types which should not be included in the reflection configuration as they are part of the static runtime hints configuration.

Closes #4248
Original pull request: #4249
2023-01-12 08:47:16 +01:00
Christoph Strobl
8bcab93588 Avoid multiple mapping iterations.
A 2nd pass is no longer needed as the context already does all the work.

Closes: #4043
Original pull request: #4240
2023-01-11 16:04:36 +01:00
Mark Paluch
1839f55055 Polishing.
Introduce HintFunction to encapsulate how hints are applied and to remove code duplications.

See #4238
Original pull request: #4243
2023-01-11 16:02:14 +01:00
Christoph Strobl
4220df5bf8 Accept index names as hint for aggregations.
Closes #4238
Original pull request: #4243
2023-01-11 16:02:05 +01:00
Christoph Strobl
95c6d1531f Fix invalid format specifier in debug statement.
Closes #4241
Original pull request: #4246
2023-01-11 15:29:22 +01:00
Christoph Strobl
b7ed099e06 Update broken links in reference documentation.
Original Pull Request: #4267
2023-01-11 13:46:50 +01:00
Maksymilian Babarowski
7e2e546e55 Update links to Spring Framework reference docs.
Closes: #4267
2023-01-11 13:46:38 +01:00
yangwenjie008
7ce2ebe26e Fix class loader issue with LazyLoadingProxyInterceptor.
Restore original behaviour that was unintentionally changed by modifications related to #4148.

Closes: #4260
Original Pull Request: #4261
2023-01-11 08:49:38 +01:00
Mark Paluch
fbf4d1baa8 Extend license header copyright years to 2023.
See #4264
2023-01-02 09:53:33 +01:00
Christoph Strobl
187f260fe4 Upgrade to MongoDB driver 4.8.1
Closes: #4251
2022-12-12 13:45:20 +01:00
Mark Paluch
04411075b4 Update CI properties.
See #4235
2022-11-18 15:31:10 +01:00
Mark Paluch
459a9c191b After release cleanups.
See #4209
2022-11-18 14:30:20 +01:00
Mark Paluch
137cba8bbb Prepare next development iteration.
See #4209
2022-11-18 14:30:19 +01:00
Mark Paluch
548cbd87b6 Release version 4.0 GA (2022.0.0).
See #4209
2022-11-18 14:26:22 +01:00
Mark Paluch
02647ad125 Prepare 4.0 GA (2022.0.0).
See #4209
2022-11-18 14:26:12 +01:00
Christoph Strobl
fe549f7254 Add Nullable annotation to parameter of overridden equals method.
Closes: #4226
Original pull request: #4277
2022-11-16 10:39:47 +01:00
Christoph Strobl
c069e094e6 Implement equals, hashCode and toString for CollectionOptions.
Closes: #4210
Original pull request: #4277
2022-11-16 10:39:14 +01:00
Christoph Strobl
62f3656ebb Replace upgrading section in documentation with links to the release notes.
Closes: #4228
2022-11-15 09:16:48 +01:00
Christoph Strobl
cbc718e03d Upgrade to MongoDB driver 4.8.0
Closes: #4201
2022-11-15 07:37:11 +01:00
Christoph Strobl
23be69b9ce Upgrade to MongoDB driver 4.8.0-rc0
See: #4201
2022-11-14 08:46:59 +01:00
Christoph Strobl
b7b5b085b3 Remove micrometer docs plugin.
See: spring-projects/spring-data-build#1836
2022-11-14 08:46:59 +01:00
Mark Paluch
2d292c50b0 After release cleanups.
See #4215
2022-11-04 15:26:39 +01:00
Mark Paluch
f959a77890 Prepare next development iteration.
See #4215
2022-11-04 15:26:37 +01:00
Mark Paluch
c04c3d66a3 Release version 4.0 RC2 (2022.0.0).
See #4215
2022-11-04 15:23:17 +01:00
Mark Paluch
b204c1b33e Prepare 4.0 RC2 (2022.0.0).
See #4215
2022-11-04 15:23:06 +01:00
Christoph Strobl
dfa029b341 Guard transaction proxy creation hints.
Closes: #4225
Related: #4221
2022-11-03 12:48:49 +01:00
Christoph Strobl
04a8c47cda Follow API changes in data-commons
Update imports of moved AOT processing types and update reactive wrapper coordinates to new location.

Closes: #4224
See: spring-projects/spring-data-commons#2708
2022-11-02 11:51:11 +01:00
Christoph Strobl
88ea57f2be Provide native hints to create transaction proxies at runtime.
Closes: #4221
2022-11-02 10:26:45 +01:00
Mark Paluch
521bbd2535 Update CI properties.
See #4215
2022-10-31 10:36:34 +01:00
Mark Paluch
0474632640 Upgrade to Java 17.0.4.1_1 and pin base image distribution.
See #4215
2022-10-31 10:27:36 +01:00
Mark Paluch
8aab5e5a01 Use correct boolean type for JSON Schema creation.
We now use the correct JSON type boolean again when creating schemas. Furthermore, we use the bool type for MongoDB $type queries.

Closes #4220
2022-10-27 10:16:58 +02:00
Christoph Strobl
3db5fc728e Polishing.
See: #4211
Original pull request: #4212
2022-10-24 15:11:25 +02:00
Christoph Strobl
b027f15a4c Add missing runtime hint for QuerydslMongoPredicateExecutor.
Closes: #4211
Original pull request: #4212
2022-10-24 15:11:10 +02:00
Mark Paluch
fd0a554d59 Polishing.
Use existing constants.

See #4218
2022-10-24 15:04:50 +02:00
Marcin Grzejszczak
d4daa305a8 Align the context propagation entries with the rest of the portfolio.
Closes #4218
2022-10-24 15:04:33 +02:00
Mark Paluch
2d63d6006d Align conventions with OpenTelemetry spec.
See: #4216
2022-10-21 11:49:03 +02:00
Mark Paluch
5007e68cc1 Polishing.
See: #4216
2022-10-21 11:49:03 +02:00
Mark Paluch
3ea4e0f9dd Update documentation.
See: #4216
2022-10-21 11:49:03 +02:00
Greg L. Turnquist
e9ac77c058 Improve configuration support for Observability integration.
Closes: #4216
2022-10-21 11:27:58 +02:00
Christoph Strobl
daef8b6e8e Add missing reflection hints for generated cglib proxies.
Closes: #4217
2022-10-20 15:59:06 +02:00
Mark Paluch
f671a9bd43 After release cleanups.
See #4175
2022-10-13 17:31:16 +02:00
Mark Paluch
57b52862c8 Prepare next development iteration.
See #4175
2022-10-13 17:31:15 +02:00
Mark Paluch
af917b9465 Release version 4.0 RC1 (2022.0.0).
See #4175
2022-10-13 17:24:25 +02:00
Mark Paluch
ee545487b8 Prepare 4.0 RC1 (2022.0.0).
See #4175
2022-10-13 17:24:03 +02:00
Mark Paluch
240e53794c Fix Javadoc.
See #4139
Original pull request: #4182.
2022-10-12 15:59:33 +02:00
Christoph Strobl
7b6a06888d Update javadoc.
See: #4184
See: #4197
Original pull request: #4203.
2022-10-12 15:25:13 +02:00
Christoph Strobl
034a3528af Preserve given Id on insert.
This commit fixes an issue where an existing Id got replaced with a generated one when using MongoId annotation.

Closes: #4184
Closes: #4197
Original pull request: #4203.
2022-10-12 15:24:50 +02:00
Christoph Strobl
ff28789507 Polishing.
See #4139
Original pull request: #4182.
2022-10-12 15:12:42 +02:00
Christoph Strobl
cdfdeafdac Update aggregation reference documentation.
See #4139
Original pull request: #4182.
2022-10-12 15:12:38 +02:00
Christoph Strobl
16a35e0329 Add support for $densify aggregation stage.
See #4139
Original pull request: #4182.
2022-10-12 15:12:38 +02:00
Christoph Strobl
79f05c3d7f Move Expr operator one level up.
The Expr operator should be held within ExpressionOperators not its factory.

See #4139
Original pull request: #4182.
2022-10-12 15:12:37 +02:00
Christoph Strobl
9217821472 Add support for $locf aggregation operator.
See #4139
Original pull request: #4182.
2022-10-12 15:12:37 +02:00
Christoph Strobl
8d223abd05 Add support for $tsSecond aggregation operator.
See #4139
Original pull request: #4182.
2022-10-12 15:12:37 +02:00
Christoph Strobl
6a973b245f Add support for $tsIncrement aggregation operator.
See #4139
Original pull request: #4182.
2022-10-12 15:12:37 +02:00
Christoph Strobl
714b23e0ce Add support for $sortArray aggregation operator.
See #4139
Original pull request: #4182.
2022-10-12 15:12:37 +02:00
Christoph Strobl
d4a6614c11 Add support for $setField aggregation operator.
See #4139
Original pull request: #4182.
2022-10-12 15:11:48 +02:00
Christoph Strobl
82ce0abe1a Add support for $getField aggregation operator.
See #4139
Original pull request: #4182.
2022-10-12 15:11:46 +02:00
Christoph Strobl
dec7c125d6 Add support for $dateTrunc aggregation operator.
See #4139
Original pull request: #4182.
2022-10-12 15:11:43 +02:00
Christoph Strobl
db12c4ba5a Add support for $dateSubtract aggregation operator.
See #4139
Original pull request: #4182.
2022-10-12 15:11:41 +02:00
Christoph Strobl
5bbe481e98 Add support for $minN aggregation operator.
See #4139
Original pull request: #4182.
2022-10-12 15:11:38 +02:00
Christoph Strobl
fb39c31986 Add support for $maxN aggregation operator.
See #4139
Original pull request: #4182.
2022-10-12 15:11:31 +02:00
Christoph Strobl
dd446472bc Polishing.
See #4139
Original pull request: #4182.
2022-10-12 15:11:22 +02:00
Christoph Strobl
72d82d3083 Add support for $top & $topN aggregation operators.
Closes #4139
Original pull request: #4182.
2022-10-12 15:11:20 +02:00
Christoph Strobl
cdfe2a0b59 Add support for $lastN aggregation operator.
Closes #4139
Original pull request: #4182.
2022-10-12 15:11:18 +02:00
Christoph Strobl
5525a4fbf9 Add support for $firstN aggregation operator.
Closes #4139
Original pull request: #4182.
2022-10-12 15:11:15 +02:00
Christoph Strobl
59464f3b3c Add support for $bottomN aggregation operator.
Closes #4139
Original pull request: #4182.
2022-10-12 15:11:09 +02:00
Christoph Strobl
052cfdfd45 Add support for $bottom aggregation operator.
Closes #4139
Original pull request: #4182.
2022-10-12 15:10:40 +02:00
Christoph Strobl
b31c21bb91 Upgrade to MongoDB driver 4.8.0-beta0.
Closes: #4200
2022-10-11 16:47:23 +02:00
Christoph Strobl
5b6e5ca568 Update tests.
Original Pull Request: #4196
2022-10-11 11:53:26 +02:00
gongxuanzhang
1a9136c0c1 Fix json schema type name for boolean.
Was boolean should have been bool.

Closes: #4196
2022-10-11 11:53:25 +02:00
Mark Paluch
59753bb55a Adapt to changed AOT packages in Spring Data Commons.
Closes #4199
2022-10-11 11:39:00 +02:00
Christoph Strobl
8d963fc5da Add option to configure change stream behaviour at collection creation time.
Introduce CollectionChangeStreamOptions which allows to define the changeStreamPreAndPostImages of the createCollection command.

Original Pull Request: #4193
2022-10-10 11:54:32 +02:00
Christoph Strobl
c1de745014 Polishing.
Update javadoc, format imports and add issue references.

Original Pull Request: #4193
2022-10-10 11:54:08 +02:00
myroslav.kosinskyi
aa35aaeb70 Add fullDocumentBeforeChange support for change streams.
Closes: #4187
Original Pull Request: #4193
2022-10-10 11:53:39 +02:00
Mark Paluch
a5725806f5 Remove references to ClassTypeInformation from TypeInformation.
Closes #4195
2022-10-06 16:21:30 +02:00
Christoph Strobl
d715414683 Switch to micrometer 1.10 snapshots.
Follow signature changes.

See: #4191
See: spring-projects/spring-data-build#1810
2022-10-06 15:44:51 +02:00
Christoph Strobl
f2c2451b7d Add hint how to use $search aggregation operator to reference documentation.
Closes: #4183
2022-10-06 13:56:57 +02:00
Christoph Strobl
5b8d0d08ee Update reactive transaction sample in reference documentation.
Closes: #4190
2022-10-06 13:03:56 +02:00
Christoph Ahlers
18186f26e2 Remove unused imports.
Closes: #4178
2022-10-06 10:21:50 +02:00
Christoph Ahlers
10acc14c14 Fix javadoc parameter names.
Closes: #4179
2022-10-04 12:31:34 +02:00
Wan Bachtiar
87effb9013 Fix typo in reference documentation.
Closes: #4180
2022-10-04 12:24:23 +02:00
Mark Paluch
19819680f9 Adopt to SLF4J 2.0 upgrade.
Exclude transitive Micrometer Test dependencies that ship outdated SLF4J implementations.

Closes #4189
2022-09-30 13:38:52 +02:00
Mark Paluch
2d2f67cc93 Prefer Java configuration over XML.
Closes #4186
2022-09-28 15:29:10 +02:00
Seungwoo Jo
e9818fe11a Fix documentation typo in BasicQuery.
Closes #4169
Original pull request: #4170.
2022-09-21 11:15:12 +02:00
Christoph Strobl
a63db5586c Add missing aggregation system variables.
Move inner class SystemVariable to upper level and add missing values (NOW, CLUSTER_TIME, DECEND, PRUNE, KEEP & SEARCH_META)

Original pull request: #4176.
Closes #4145
2022-09-21 10:51:00 +02:00
Mark Paluch
68ab74a5bf Polishing.
Reformat code.

See #4004
Original pull request: #4006.
2022-09-21 10:48:22 +02:00
Christoph Strobl
de33734118 Polishing
Update Javadoc to mention unit of measure for min/maxDistance depending on usage of geoJson.
Also remove unused imports from tests

See #4004
Original pull request: #4006.
2022-09-21 10:48:22 +02:00
Christoph Strobl
c272c7317e Fix rewrite near & nearSphere count queries using geoJson to geoWithin.
$near and $nearSphere queries are not supported via countDocuments and the used aggregation match stage and need to be rewritten to $geoWithin. The existing logic did not cover usage of geoJson types, which is fixed now. In case of nearSphere it is also required to convert the $maxDistance argument (given in meters for geoJson) to radians which is used by $geoWithin $centerSphere.

Closes #4004
Original pull request: #4006.
Related to #2925
2022-09-21 10:48:21 +02:00
Spring Builds
d7fc605f7b After release cleanups.
See #4117
2022-09-19 14:39:07 +00:00
Spring Builds
3b805b9e03 Prepare next development iteration.
See #4117
2022-09-19 14:38:55 +00:00
Spring Builds
91cca3f2c4 Release version 4.0 M6 (2022.0.0).
See #4117
2022-09-19 14:15:22 +00:00
Spring Builds
2de6384d0f Prepare 4.0 M6 (2022.0.0).
See #4117
2022-09-19 14:12:56 +00:00
Christoph Strobl
ab1c0ff7b8 Apply conversion on document reference lookup using nested property.
Closes #4033
Original pull request: #4044.
2022-09-19 09:57:24 +02:00
Christoph Strobl
ae2846c5bf Generate and convert id on insert if explicitly defined.
We now make sure to provide an id value that matches the desired target type when no id is set, and the property defines an explicit conversion target.
Previously a new ObjectId would have been generated which leads to type inconsistencies when querying for _id.

Closes #4026
Original pull request: #4057.
2022-09-19 09:47:18 +02:00
Christoph Strobl
e88c9cf791 Fix issue with reference conversion in updates.
We now make sure to convert references in update operations targeting collection like fields when using eg. the push modifier.

Closes #4041
Original pull request: #4045.
2022-09-19 08:54:26 +02:00
Christoph Strobl
fadca10f62 Support @DocumentReference via Querydsl.
Closes #4037
Original pull request: #4069.
2022-09-16 15:57:30 +02:00
Mark Paluch
40320136f3 Polishing.
See #4061
Original pull request: #4062.
2022-09-16 14:52:00 +02:00
Christoph Strobl
bc575de3b0 Improve exception message when deriving collection name from type.
We now provide a better worded exception message when trying to derive the collection name for a type that is not considered a user types (such as org.bson.Document).
Update the Javadoc to hint to the error.

Closes #4061
Original pull request: #4062.
2022-09-16 14:51:54 +02:00
Christoph Strobl
09b2afa79d Initialize lists with size where possible.
Closes #3941
Original pull request: #3974.
2022-09-16 14:45:34 +02:00
Mark Paluch
96b564eb9a Polishing.
Reformat code.

See #4167.
Original pull request: #4168.
2022-09-16 14:40:34 +02:00
Christoph Strobl
38390d3475 Fix usage of change stream option startAfter.
We now make sure to apply the token to startAfter method of the driver. Before this change it had been incorrectly applied to resumeAfter.

Closes #4167.
Original pull request: #4168.
2022-09-16 14:40:27 +02:00
Mark Paluch
6937bb519b Polishing.
Move off more deprecated API.

See #4164
Original pull request: #4165.
2022-09-16 11:11:17 +02:00
Christoph Strobl
6e4d463053 Move off deprecated API.
Closes #4164
Original pull request: #4165.
2022-09-16 11:11:12 +02:00
Mark Paluch
a9d2050806 Polishing.
Fix generics. Add warning suppressions for nullability checks.

See: #4104
Original pull request: #4156.
2022-09-14 14:06:44 +02:00
Christoph Strobl
6676389062 Fix GeoJson polygon conversion for polygons with inner ring.
Closes: #4104
Original pull request: #4156.
2022-09-14 14:06:35 +02:00
Mark Paluch
81f85b8cca Polishing.
Tweak Javadoc, make ViewOptions.collation final.

See: #2594
Original pull request: #4142.
2022-09-14 11:31:14 +02:00
Christoph Strobl
77f318bd77 Add support to create views via reactive/template API.
This commit introduces support to create MongoDB Views directly via the Reactive-/MongoOperations API.

Closes: #2594
Original pull request: #4142.
2022-09-14 11:30:24 +02:00
Brian Clozel
7c7e70418f Replace deprecated StreamUtils API
As of spring-projects/spring-framework#29125,
`StreamUtils..emptyInput()` is deprecated in favor of
`InputStream.nullInputStream()` from the JDK.

Closes: #4160
2022-09-14 08:14:06 +02:00
Mark Paluch
44a1123034 Adopt to changed Mockk artifact name.
Closes #4161
2022-09-12 14:08:14 +02:00
Mark Paluch
e487c08b0c Polishing.
Reformat pom.xml

See #4161
2022-09-12 10:18:38 +02:00
Mark Paluch
a002d30aa9 Polishing.
Reformat pom.xml

See #4161
2022-09-12 10:17:58 +02:00
Tommy Ludwig
36ddd26edc Adapt to SampleTestRunner refactor.
See: micrometer-metrics/tracing#57
Closes: #4159
2022-09-09 19:13:57 +02:00
Tommy Ludwig
6197655e98 Adapt to ObservationConvention location change
See: micrometer-metrics/micrometer#3387
Closes: #4158
2022-09-09 19:06:28 +02:00
Christoph Strobl
929faea88b Add snapshot plugin repository for micrometer docs.
See: #4151.
2022-09-07 14:51:57 +02:00
Greg L. Turnquist
1fe1c13531 Upgrade to Micrometer 1.10.0-SNAPSHOT.
Closes #4151.
2022-09-07 12:17:16 +02:00
Kirill Gavrilov
838ddb5d26 Align signature of Kotlin extension functions to match Java API.
Closes: #4153
Original Pull Request: #4154
Related issues: #2602 #3187
2022-09-07 09:48:48 +02:00
Christoph Strobl
33c7f0980f Remove usage SynthesizedAnnotation.
Closes: #4155
2022-09-07 08:54:41 +02:00
Mark Paluch
4bbc443a0e Polishing.
Refine assertions.

See #4132
Original pull request: #4147.
2022-08-25 15:45:29 +02:00
Christoph Strobl
655dbc9783 Favor relaxed type mapping over strict one for aggregateStream.
Align aggregation context usage of aggregate and aggregate stream methods.

Closes #4132
Original pull request: #4147.
2022-08-25 15:45:13 +02:00
Christoph Strobl
0d752fd6e6 Introduce dedicated Collation annotation.
The Collation annotation mainly serves as a meta annotation that allows common access to retrieving collation values for annotated queries, aggregations, etc.

Original Pull Request: #4131
2022-08-25 09:03:43 +02:00
Christoph Strobl
8aabf2fa5e Polishing.
Resolve collation from template expression & update issue references + Javadoc.

Original Pull Request: #4131
2022-08-25 09:00:51 +02:00
Stefan Tirea
ff9d338bd7 Add collation for an index via @CompoundIndex and @Index annotations.
Closes #3002, closes #4130

Original Pull Request: #4131
2022-08-25 09:00:17 +02:00
Mark Paluch
2a4ee12363 Document BulkOperations limitations.
Closes #4082
2022-08-23 15:39:59 +02:00
Christoph Strobl
a66438fc20 Resolve cglib proxies during AOT processing.
We now make sure to run the enhancer during AOT which allows the infrastructure to pick up the generated type.
Along the lines we removed the no longer supported asserts for class proxies and followed changes in FW6.

Closes: #4148
2022-08-23 11:48:23 +02:00
Mark Paluch
0ccc037b8e Polishing.
Introduce JUnit extension to declare tests that dirty or provide their state.

See #3817
Original pull request: #3987.
2022-08-23 10:00:16 +02:00
Christoph Strobl
00792192c3 Close clients created during tests.
See #3817
Original pull request: #3987.
2022-08-23 09:54:29 +02:00
Christoph Strobl
e064b505c9 Prevent sync client from being created in reactive test config.
Closes #3817
Original pull request: #3987.
2022-08-23 09:53:58 +02:00
Christoph Strobl
7df2bdf8ff Upgrade to MongoDB driver 4.7.1
Closes: #4144
2022-08-22 07:59:57 +02:00
Mark Paluch
2f9fc1618e Use mongosh instead of mongo CLI.
Switch from the deprecated command to its replacement.

See #4138
2022-08-17 12:56:26 +02:00
Mark Paluch
9e2aecf4ae Polishing.
Fix required Java version.

See #4140
2022-08-17 10:58:13 +02:00
Mark Paluch
c32c4beb59 Remove new & noteworthy section in favor of our release notes.
The release notes now outline new and noteworthy changes.

Closes #4140
2022-08-17 10:51:01 +02:00
Mark Paluch
d48f3ec535 Polishing.
Use && syntax to catch commands that exit with non-success exit codes.

See #4139
2022-08-17 10:44:11 +02:00
Mark Paluch
5f16aecd13 Assert compatibility with MongoDB 6.0.
Closes #4138
2022-08-17 10:42:57 +02:00
Mark Paluch
5fc49b1649 Polishing.
Encapsulate nested object lookup. Refine method signatures and tweak Javadoc.

See #4098
Original pull request: #4133.
2022-08-05 15:59:31 +02:00
Christoph Strobl
1e7dc7ce66 Fix non-association mapping when id value matches already resolved instance of same type.
This commit ensures to fully resolve non association values from the given source document instead of trying attempt a by id lookup in already resolved instances.

Closes: #4098
Original pull request: #4133.
2022-08-05 15:59:04 +02:00
Christoph Strobl
234783f442 Allow referencing the $id field of dbrefs within an aggregation pipeline.
Closes: #4123
Original pull request: #4125.
2022-08-05 14:19:29 +02:00
Sojin
3429350964 Fix AKNOWLEDGED typo in reference documentation.
Two typos found have been updated

Closes #4135
2022-08-05 14:07:54 +02:00
Mark Paluch
d130984bdc Allow disabling entity lifecycle events.
We now support disabling lifecycle events through the Template API to reduce the framework overhead when events are not needed.

Closes #4107
2022-07-20 16:07:01 +02:00
Christoph Strobl
f5378bf825 Upgrade to MongoDB driver 4.7.0
Closes: #4124
2022-07-20 08:13:53 +02:00
Mark Paluch
21057c3d17 Fix DTO projection instantiation.
We now correctly instantiate DTO projection classes by using the actual constructor argument type. Previously, we did not update the conversion context to fetch the correct type but used the type of the DTO projection class instead of the constructor argument.

Closes #4120
2022-07-19 11:17:40 +02:00
Christoph Strobl
d0a98eb71d After release cleanups.
See #4054
2022-07-15 15:30:53 +02:00
Christoph Strobl
bc95c4d390 Prepare next development iteration.
See #4054
2022-07-15 15:30:45 +02:00
Christoph Strobl
d56a4ea77d Release version 4.0 M5 (2022.0.0).
See #4054
2022-07-15 15:18:29 +02:00
Christoph Strobl
5a09626cbf Prepare 4.0 M5 (2022.0.0).
See #4054
2022-07-15 15:17:56 +02:00
John Blum
029291a1dd Adapt to repackaging of the AOT RuntimeHintsPredicate.
Closes #4111.
2022-07-12 18:05:46 -07:00
Mark Paluch
989a2596cb Upgrade to MongoDB driver 4.7.0-beta0.
Closes #4110
2022-07-12 15:40:36 +02:00
Greg L. Turnquist
f5c520dbc8 Upgrade Micrometer's tracing artifact to micrometer-tracing.
Closes #4106.
2022-07-11 08:24:41 -05:00
Mark Paluch
80c843eb20 Update README.adoc
See #4054
2022-07-11 15:06:12 +02:00
Christoph Strobl
9b136537c0 Simplify auditing configuration.
Use IsNewAwareAuditingHandler factory method to avoid exposing additional beans.

See: #4022
2022-07-08 08:57:34 +02:00
Mark Paluch
d334c5a44c Polishing.
Adopt to Framework changes.
Simplify auditing bean registration.
Remove ImportRuntimeHints in EnableMongoAuditing.
Refine ManagedTypes bean definitions.
Consistently use mongo as bean name prefix. Depend on store-specific ManagedTypes.
Rewrite ReactiveMongoAuditingRegistrar to avoid inner beans.
Reduce AOT processor visibility. Cleanup imports. Improve type naming. Update Javadoc.

Original Pull Request: #4093
2022-07-05 09:55:41 +02:00
Christoph Strobl
cfd55be95b Add AOT repository support
We now use the AOT infrastructure of Spring Framework 6 and data commons to provide AOT support building the foundation for native image compilation.
Additionally we register hints for GraalVM native image.

See: #4022
Original Pull Request: #4093
2022-07-05 09:55:10 +02:00
Mark Paluch
079c5a95aa Adopt test to Spring Framework 6 changes.
See #4054
2022-07-05 07:38:35 +02:00
Mark Paluch
3f6821f11f Adopt to Reactor 2022.0.0-M4 changes.
Closes #4100
2022-07-04 14:28:55 +02:00
Mark Paluch
1a868ae35e Avoid duplicate bean registrations in MappingMongoConverterParser.
We now ensure to not override `ValidatingMongoEventListener` and `LocalValidatorFactoryBean` bean definitions by avoiding duplicate registrations and checking whether a bean with the given name is already registered.

Closes #4087
2022-06-28 10:24:56 +02:00
Mark Paluch
248bcfa177 Polishing.
Simplify code.

Original pull request: #4059.
See #4038
2022-06-27 15:42:55 +02:00
Christoph Strobl
ee076ec02f Simplify usage of user provided aggregation operations.
Introduce Aggregation.stage which allows to use a plain JSON String or any valid Bson representation to be used within an aggregation pipeline stage, without having to implement AggregationOperation directly.
The change allows to make use of driver native builder API for aggregates.

Original pull request: #4059.
Closes #4038
2022-06-27 15:42:55 +02:00
Mark Paluch
1184d6ee2d Upgrade to Kotlin 1.7.
Adopt to stricter nullability checks.

Closes #4096
2022-06-24 11:53:12 +02:00
Christoph Strobl
062b4e8757 Provide Module Identifier via MongoRepositoryConfigurationExtension
Closes: #4092
2022-06-21 08:00:06 +02:00
Christoph Strobl
30a417d810 Retain parameter type when binding parameters in annotated Query/Aggregation.
This commit ensures the parameter type is preserved when binding parameters used within the value of the Query or Aggregation annotation

Closes: #4089
2022-06-20 10:37:49 +02:00
Christoph Strobl
1671f960b6 Upgrade to MongoDB driver 4.6.1
Closes: #4081
2022-06-20 09:10:40 +02:00
Mark Paluch
d4cce9ac00 Wrap SpEL documentation with admonition.
Closes #4085
2022-06-14 09:11:46 +02:00
Mark Paluch
8f9576aa42 Polishing.
Reformat asciidoc source.

See #4085
2022-06-14 09:04:20 +02:00
John Blum
f15fd2a418 Remove punctuation in Exception messages.
Closes #4079.
2022-06-08 15:21:22 -07:00
Mark Paluch
01656db002 Upgrade to Maven Wrapper 3.8.5.
See #4073
2022-06-03 09:32:40 +02:00
John Blum
84faff6bd4 Remove Docker Registry login.
Closes #4056.
2022-05-16 12:55:12 -07:00
Greg L. Turnquist
d72e1531d3 Adapt to changes in Micrometer APIs.
Micrometer has updated some of its APIs and we must adjust.

Closes: #4055
2022-05-16 14:34:50 -05:00
Mark Paluch
ac59cf930a Update driver compatibility matrix.
Closes #4052
2022-05-16 15:11:38 +02:00
Christoph Strobl
7bdc8d3aac Fix pom.xml formatting.
This commit reverts formatting changes introduced via 140fb2e9ea.

See #4005
2022-05-13 12:59:40 +02:00
Christoph Strobl
47548a21ea After release cleanups.
See #4005
2022-05-13 10:53:26 +02:00
Christoph Strobl
5aaa8f79e7 Prepare next development iteration.
See #4005
2022-05-13 10:53:23 +02:00
Christoph Strobl
1a77b1bc56 Release version 4.0 M4 (2022.0.0).
See #4005
2022-05-13 10:43:59 +02:00
Christoph Strobl
140fb2e9ea Prepare 4.0 M4 (2022.0.0).
See #4005
2022-05-13 10:43:20 +02:00
Jay Bryant
b571c8958d Editing pass for new content in reference documentation.
Closes: #4049
2022-05-11 05:38:24 +02:00
Christoph Strobl
8d54cae54d Polishing.
Update Query javadoc.

Original Pull Request: #3999
2022-05-10 16:33:19 +02:00
Raul Mello Silva
14a71f0498 Update Query.limit javadoc.
This commit explains usage of Query.limit(int), which will be set to unlimited when set to zero or a negative value.

Closes: #3999
2022-05-10 16:19:07 +02:00
Christoph Strobl
14c265f3a1 Provide additional meta information via pom.xml
Add scm & issueManagement.

Closes: #4048
2022-05-10 12:31:29 +02:00
nniesen
440a289ac6 Update spring.io project urls.
This commit updates outdated projects.spring.io links to spring.io/projects.

Closes: #4042
2022-05-09 13:57:49 +02:00
John Blum
9663a2227b Adapt to API changes in PropertyValueConverters.
Closes #4040.
2022-05-02 17:19:17 -07:00
Mark Paluch
b134e1916d Upgrade to MongoDB driver 4.6.0.
Closes #4027
2022-04-19 10:05:37 +02:00
Greg L. Turnquist
65b02f92b4 Use updated coordinates for Hibernate Validator.
See #4024.
2022-04-15 10:45:58 -05:00
Greg L. Turnquist
667b71e073 Switch to Micrometer 1.10's tracing APIs.
Micrometer Tracing 1.10 has some breaking APIs.

See #4023.
2022-04-15 10:04:41 -05:00
Mark Paluch
225dbee15f Simplify dependency version arrangement.
We now inherit the version number and repositories from the parent pom.

See #4017
2022-04-07 09:53:10 +02:00
Mark Paluch
c04ceb163b Polishing.
Reformat code.

See #4017
2022-04-07 09:44:42 +02:00
Greg L. Turnquist
711ac343fe Fix Micrometer-based deployment issues.
When deploying to artifactory, a Micrometer-based plugin can't be found.

See #4017.
2022-04-06 09:25:44 -05:00
Mark Paluch
852a4ecc59 Polishing.
Refine default conversions creation.

See #4014
Original pull request: #4015.
2022-04-05 10:07:51 +02:00
Christoph Strobl
7ab2428c64 Make sure to initialize PropvertyValueConversions in Converter setup.
Closes #4014
Original pull request: #4015.
2022-04-05 10:07:46 +02:00
Oliver Drotbohm
350acf66bc Adapt to API changes in Spring Data Commons.
spring-projects/spring-data-commons#2518 introduced TypeInformation.getTypeDescriptor() which we need to implement in our custom FieldTypeInformation.
2022-04-04 18:21:04 +02:00
Christoph Strobl
ab94a94b2e Upgrade to MongoDB driver 4.5.1
Resolves: #4013
2022-04-04 10:20:20 +02:00
Christoph Strobl
4c77763cd3 Introduce Observability with Micrometer and Micrometer Tracing.
See #3942.
2022-03-29 13:09:07 -05:00
Christoph Strobl
f197953480 Update build triggers.
See: #4005
2022-03-24 13:53:25 +01:00
Mark Paluch
44afd4939e After release cleanups.
See #4003
2022-03-22 14:07:38 +01:00
Mark Paluch
575917435e Prepare next development iteration.
See #4003
2022-03-22 14:07:36 +01:00
Mark Paluch
2db55ab0aa Release version 4.0 M3 (2022.0.0).
See #4003
2022-03-22 14:00:23 +01:00
Mark Paluch
79602b7dbe Prepare 4.0 M3 (2022.0.0).
See #4003
2022-03-22 14:00:02 +01:00
Mark Paluch
d5d2371b9e After release cleanups.
See #3937
2022-03-21 16:44:41 +01:00
Mark Paluch
c95e8a5748 Prepare next development iteration.
See #3937
2022-03-21 16:44:39 +01:00
Mark Paluch
f0c0a86118 Release version 4.0 M2 (2022.0.0).
See #3937
2022-03-21 16:35:08 +01:00
Mark Paluch
3d82e12e6b Prepare 4.0 M2 (2022.0.0).
See #3937
2022-03-21 16:34:37 +01:00
Mark Paluch
8672808222 Polishing.
Reformat code. Tweak documentation wording.

See #3596
Original pull request: #3982.
2022-03-21 09:20:47 +01:00
Christoph Strobl
29fb085d8b Add support for PropertyValueConverters.
Closes: #3596
Original pull request: #3982.
2022-03-21 09:20:34 +01:00
Mark Paluch
15cac49f9c Polishing.
Refine API naming towards merge/property instead of combine/specify. Tweak documentation. Introduce Resolution.ofValue(…) for easier creation.

See #3870
Original pull request: #3986.
2022-03-18 14:11:35 +01:00
Christoph Strobl
946deac48c Support generating JsonSchema for Polymorphic fields.
This commit introduces MergedJsonSchema and MergedJsonSchemaProperty that can be used to merge properties of multiple objects into one as long as the additions do not conflict with another (eg. due to usage of different types).
To resolve previously mentioned errors it is required to provide a ConflictResolutionFunction.

Closes #3870
Original pull request: #3986.
2022-03-18 14:11:35 +01:00
Mark Paluch
02229f291c Polishing.
Reformat code.

See #3998
2022-03-16 16:44:06 +01:00
Mark Paluch
1009491920 Create a new conversion context for projection properties.
We now create a new conversion context to ensure that we use the correct property type to avoid type retention when mapping complex objects within a projection.

Closes #3998
2022-03-16 16:29:14 +01:00
Mark Paluch
05730ded1b Fix CI trigger.
Use correct Spring Data Commons version as build trigger.

See #3973
2022-03-15 14:38:54 +01:00
Mark Paluch
612845f59c Polishing.
Extract CreateCollectionOptions conversion to EntityOperations to unify collection creation. Adopt tests.

See #3984
Original pull request: #3990.
2022-03-11 15:21:05 +01:00
Mark Paluch
1f06954952 Polishing.
Add missing Override annotations to template API methods.

See #3984
2022-03-11 15:20:20 +01:00
Christoph Strobl
7bcf0322d2 Propagate time series options correctly.
This commit fixes an issue when creating a collection via MongoTemplate without passing on type information. In this case potential time series information was lost.

Closes #3984
Original pull request: #3990.
2022-03-11 15:18:58 +01:00
Mark Paluch
7dd2f350eb Polishing.
Remove duplicate dependency declaration.

See: #3522
2022-03-11 14:10:49 +01:00
Mark Paluch
e433375cac Polishing.
Reorder methods. Add links to Javadoc. Tweak wording.

See: #3522
Original pull request: #3951.
2022-03-11 14:09:58 +01:00
Christoph Strobl
d16013aa6b Allow to estimate document count.
This commit introduce an option that allows users to opt in on using estimatedDocumentCount instead of countDocuments in case the used filter query is empty.
To still be able to retrieve the exact number of matching documents we also introduced MongoTemplate#exactCount.

Closes: #3522
Original pull request: #3951.
2022-03-11 14:06:30 +01:00
Christoph Strobl
dab5473740 Modify visibility of methods in TypedJsonSchemaObject.
Change visibility to public as it should have been in first place.

Closes: #3989
2022-03-10 09:23:25 +01:00
sangyongchoi
e6fce75dfd Remove duplicate condition in GeoConverters.
Closes: #3981
2022-03-03 13:29:24 +01:00
Mark Paluch
e75f022844 Update CI properties.
See #3937
2022-02-23 14:33:13 -06:00
Christoph Strobl
611ece049b Serialize values for debug output safely in AbstractMongoEventListener.
We now make sure that codec configuration will not cause an exception when debug logging is turned on.

Resolves: #3968
Original Pull Request: #3970
2022-02-18 10:15:28 +01:00
Christoph Strobl
be2286edf7 Update copyright year to 2022.
See: #3966
2022-02-17 10:49:44 +01:00
Christoph Strobl
b99648672b Introduce Update annotation.
Switch update execution to an annotation based model that allows usage of both the classic update as well as the aggregation pipeline variant. Add the reactive variant of it.
Make sure to allow parameter binding for update expressions and verify method return types.
Update Javadoc and reference documentation.

See: #2107
Original Pull Request: #284
2022-02-17 10:31:46 +01:00
Thomas Darimont
28708ce24e Add support for modifying documents via repository method.
We now support findAndModify operations on derived query methods.

Closes: #2107
Original Pull Request: #284
2022-02-17 10:29:37 +01:00
Christoph Strobl
1c6c703640 Deprecate mapReduce.
Closes: #3945
2022-02-16 14:45:01 +01:00
blu10ph
67b1fe5fbc Avoid obtaining mapped sort multiple times for mapReduce.
Apply already mapped sort for map reduce instead of running the source document through the mapping layer again.

Closes: #3960
2022-02-16 14:42:57 +01:00
Christoph Strobl
4f6501f140 Update GeoJson section in reference documentation.
Mention the relation of Point/GeoJsonPoint x/y coordinates to longitude/latitude.

Original Pull Request: #3956
2022-02-16 14:42:19 +01:00
sangyongchoi
2a3f746cb6 Update GeoJsonPoint Javadoc.
Mention x -> longitude, y -> latitude relation.

Closes: #3956
2022-02-16 14:41:33 +01:00
Mark Paluch
90b8ba7246 Polishing.
Extract docker credentials into properties file.
Use tabs for indentation instead of spaces.

See #3949
2022-02-16 13:36:39 +01:00
Oliver Drotbohm
f12648af4c Adapt to API changes regarding object creation metadata. 2022-02-15 17:37:58 +01:00
Greg L. Turnquist
e812f89b47 Update CI properties.
See #3937
2022-02-15 09:00:21 -06:00
Christoph Strobl
f96d700d8d Favor Base64Utils over bson internal Base64 type.
org.bson.internal.Base64 is no longer available in MongoDB driver 4.5.0.

Related to: #3962
2022-02-14 11:09:26 +01:00
Christoph Strobl
32e7f2032d Upgrade to MongoDB driver 4.5.0
Closes: #3962
2022-02-14 11:09:14 +01:00
Mark Paluch
43ac1984ab Adapt repository to List-based interface variants.
Closes #3964
2022-02-14 11:07:27 +01:00
Greg L. Turnquist
28f262309c Use Harbor Proxy for containers.
Leverage internal infrastructure for pulling Docker container images. Reduces pressure on Docker Hub and reduces risk of hitting rate limits.

See #3954.
Related https://github.com/spring-projects/spring-data-build/issues/1630.
2022-02-07 10:59:50 -06:00
Mark Paluch
eefe6b3b21 Update CI properties.
See #3937
2022-02-07 09:32:15 +01:00
Mark Paluch
d0f2ca9efc Polishing.
Refine build script.

See #3949
2022-02-04 08:49:49 +01:00
Mark Paluch
e6c8ee037a Polishing.
Extract docker credentials into properties file.
Use tabs for indentation instead of spaces.

See #3949
2022-02-04 08:46:05 +01:00
Christoph Strobl
e63013deac Remove previously deprecated API.
This commit removes and moves off deprecated API.
Additionally some blocks got deprecated due to changes in MongoDB server API.

Resolves: #3952
2022-02-03 16:44:03 +01:00
Mark Paluch
2367379b6d Use Java 8 Stream as return type for Template operations returning a stream.
We now use Stream instead of CloseableIterator for easier stream creation.

Closes: #3944
Original Pull Request: #3946
2022-02-03 08:30:27 +01:00
Mark Paluch
a1c483f2e1 After release cleanups.
See #3927
2022-02-03 08:08:50 +01:00
Mark Paluch
64b8b500ae Prepare next development iteration.
See #3927
2022-02-03 08:08:50 +01:00
Mark Paluch
2d15e37bc7 Release version 4.0 M1 (2022.0.0).
See #3927
2022-02-03 08:08:50 +01:00
Mark Paluch
54655b88c0 Prepare 4.0 M1 (2022.0.0).
See #3927
2022-02-03 08:08:49 +01:00
Jens Schauder
cd395e3324 Remove Eclipse Non-Javadoc comments.
Closes #3924
2022-02-03 08:08:00 +01:00
Mark Paluch
33bdbbe851 Polishing. 2022-02-03 08:08:00 +01:00
Christoph Strobl
9f1448df44 Drop support for RxJava 1 and 2.
Closes: #3839
2022-02-03 08:08:00 +01:00
Christoph Strobl
e3a4bada63 Move to Jakarta EE9
Closes: #3830
2022-02-03 08:08:00 +01:00
Christoph Strobl
dcdf3a2365 Prepare Spring Data MongoDB 4.x branch.
Upgrade to data-commons 3.0 and Java 17 (still source level 16 due to asm).
Remove support for threeten, joda-time.
Transition to PersistentEntitiesFactoryBean from data-commons.
Update build to MongoDB 4.4 and 5 with Java17. Remove Java8 setup.
Fix javadoc tooling error on cdi 1 vs. 2 version mix.
Disabled internal package cycle analysis as this requires transition to ArchUnit.
2022-02-03 08:07:59 +01:00
Mihail Cornescu
423e10b7bc Add IgnoreCase to repository queries documentation.
Update reference documentaion and add missing IgnoreCase keyword.

Closes: #3916
Original Pull Request: #3950
2022-02-02 13:13:10 +01:00
Greg L. Turnquist
f62feac421 Externalize build properties.
By reading a properties file from an external location, it is possible to inject a consistent set of properties from Spring Data Build. This also supports repeatable builds.

Closes #3949.
2022-01-31 16:33:45 -06:00
Christoph Strobl
bcbefa9264 Support aggregation operators $first and $last via expression method reference.
This commit registers the first(...) and last(...) methods for transformation via SpEL.
Also update reference and java documentation and add issue reference to tests.

Original Pull Request: #3866
2022-01-24 09:22:33 +01:00
Divya Srivastava
a2243536b2 Add support for $first & $last aggregation operators.
Closes: #3694
Original Pull Request: #3866
2022-01-24 09:22:27 +01:00
Christoph Strobl
a36e292158 Update aggregation StringOperators documentation.
Update reference and java documentation.
Add issue reference to tests.
Align method names and format code.

Original Pull Request: #3861
2022-01-21 10:42:19 +01:00
Divya Srivastava
494c22b192 Add support for $replaceOne & $replaceAll aggregation operators.
Closes: #3695
Original Pull Request: #3861
2022-01-21 10:40:54 +01:00
Christoph Strobl
030f12023c Support aggregation operators $acos and $acosh via expression method reference.
This commit registers the acos(...) and acosh(...) methods for transformation via SpEL.

Original Pull Request: #3858
2022-01-20 16:18:23 +01:00
Christoph Strobl
31f640a398 Polishing.
Update java doc and add issue references to tests.

Original Pull Request: #3858
2022-01-20 16:18:10 +01:00
Divya Srivastava
54f098a906 Add support for $acos & $acosh aggregation operators.
Resolves: #3707
Original Pull Request: #3858
2022-01-20 16:17:55 +01:00
Christoph Strobl
885d05965b Revert query modification in json parsing tests.
Add tests and move json string treatment into the ParameterBindingDocumentCodec.
Finally add issue references and format code.

Original Pull Request: #3907
2022-01-20 14:49:39 +01:00
rolag-it
a8a0fb5dba Fix expression defining entire query in annotated repository methods.
This fix enables defining an entire JSON-based query in Query and Aggregate annotations using a single parameter or SpEL Expression.

Resolves: #3871
Original Pull Request: #3907
2022-01-20 13:43:32 +01:00
Christoph Strobl
67edae8602 After release cleanups.
See #3936
2022-01-18 09:21:33 +01:00
Christoph Strobl
249e7746d5 Prepare next development iteration.
See #3936
2022-01-18 09:21:29 +01:00
Christoph Strobl
6a979088b5 Release version 3.4 M2 (2021.2.0).
See #3936
2022-01-18 09:09:36 +01:00
Christoph Strobl
fca629c117 Prepare 3.4 M2 (2021.2.0).
See #3936
2022-01-18 09:09:00 +01:00
Mark Paluch
dfbd1bded5 Polishing.
Run mvnw -version command in Artifactory build to display Java version.

See #3882
2022-01-17 13:55:53 +01:00
Christoph Strobl
f9e98669b9 After release cleanups.
See #3882
2022-01-14 11:08:02 +01:00
Christoph Strobl
96d4abdf24 Prepare next development iteration.
See #3882
2022-01-14 11:07:59 +01:00
Christoph Strobl
23442ef639 Release version 3.4 M1 (2021.2.0).
See #3882
2022-01-14 10:58:16 +01:00
Christoph Strobl
01b571dec9 Prepare 3.4 M1 (2021.2.0).
See #3882
2022-01-14 10:57:50 +01:00
Christoph Strobl
04ec49eb9e Avoid schema keyId uuid representation errors.
To avoid driver configuration specific UUID representation format errors (binary subtype 3 vs. subtype 4) we now directly convert the given key into its subtype 4 format.

Resolves: #3929
Original pull request: #3931.
2022-01-13 15:26:53 +01:00
Mark Paluch
d61cf8f57e Polishing.
Simplify assertions, reformat code.

See #3921
Original pull request: #3930.
2022-01-13 11:01:48 +01:00
Christoph Strobl
50a12121f2 Use index instead of iterator to map position and map keys for updates.
This commit removes usage of the iterator and replaces map key and positional parameter mappings with an index based token lookup.

Closes #3921
Original pull request: #3930.
2022-01-13 11:01:35 +01:00
Mark Paluch
998bd1f9bb Polishing.
Reformat code. Tweak documentation wording and callout syntax.

See #3914, see #3901
Original pull request: #3915.
2022-01-12 15:59:14 +01:00
Christoph Strobl
e0a57fa19b Avoid creating invalid index definitions for Map-like properties.
This commit makes sure to exclude Map like structures from index inspection unless annotated with WilcardIndexed.

Closes #3914, closes #3901
Original pull request: #3915.
2022-01-12 15:57:19 +01:00
Mark Paluch
9c78802c47 Polishing.
Add author tags, extend copyright license years, simplify tests.

See #3892
2022-01-12 15:30:36 +01:00
rolag-it
a958ffb5c8 Fix pagination with reactive fluent Querydsl query definition.
Pageable object was not passed to Query, so fetchPage retrieved erroneously the whole dataset as Page content.

Closes #3892
2022-01-12 15:30:31 +01:00
Hett
c31872d979 Avoid double call of fetch method in DefaultReferenceResolver.
This commit fixes an issue where the fetch method is called twice when looking up singe value references.

Resolves: #3918
Original Pull Request: #3919
2022-01-11 08:57:02 +01:00
Mark Paluch
212509f56a Upgrade to MongoDB driver 4.4.1.
Closes #3926
2022-01-10 08:52:57 +01:00
Mark Paluch
b348bb6679 Adopt to Mockito changes.
Closes #3923
2022-01-04 14:41:47 +01:00
Christoph Strobl
8be5dd3909 Adapt to changes in data-commons.
See: spring-projects/spring-data-commons#2514
Related to: #3894
2021-12-14 15:31:45 +01:00
Christoph Strobl
f2c4370584 Fix meta field mapping when computing fields for projections.
Related to: #3894
2021-12-14 14:58:53 +01:00
Christoph Strobl
fdff74f7b5 Polishing.
Add tests for projections on dbref properties update java- and reference documentation.

Original Pull Request: #3894
2021-12-14 11:31:00 +01:00
Mark Paluch
0070b12f95 Add general support for direct projections.
Closes: #3894
2021-12-14 11:30:45 +01:00
Mark Paluch
bafc2bebf2 Polishing.
Tweak Javadoc.

See #3898
Original pull request: #3904.
2021-12-14 09:36:19 +01:00
Christoph Strobl
7146fb33e9 Fix field inclusion in aggregation project operation.
Closes #3898
Original pull request: #3904.
2021-12-14 09:36:14 +01:00
Mark Paluch
75999d9e36 Propagate Bean ClassLoader to MongoTypeMapper.
We now set the ClassLoader from the ApplicationContext to the type mapper to ensure the type mapper has access to entities. Previously, `SimpleTypeInformationMapper` used the contextual class loader and that failed in Fork/Join-Pool threads such as parallel streams as ForkJoinPool uses the system classloader. Running e.g. a packaged Boot application sets up an application ClassLoader that has access to packaged code while the system ClassLoader does not.

Also, consistently access the MongoTypeMapper through its getter.

Closes #3905
2021-12-09 11:33:47 +01:00
John Blum
7a64025669 Edit README.
Fix punctation, change wording and correct case in build from source section.
2021-12-07 17:58:54 -08:00
John Blum
113106037a Polish for retaining the sort order when using text search sort by score.
Closes gh-3896.
2021-12-07 17:37:24 -08:00
Christoph Strobl
132834b1e6 Retain sort order when using text search sort by score.
We now make sure to capture the position to apply sort by score.
2021-12-07 17:37:10 -08:00
Christoph Strobl
36a4b7f727 Polishing - Update outdated links in Javadoc.
Original Pull Request #3883
2021-11-16 14:26:21 +01:00
Mark Paluch
a8432f5bf1 Polishing.
Remove unused fields.

Original Pull Request #3883
2021-11-16 14:26:02 +01:00
Christoph Strobl
e5a295bb8f Guard potentially expensive log message computations.
Original Pull Request #3883
2021-11-16 14:25:40 +01:00
Mark Paluch
f7cbd4264a Migrate off SLF4J to Spring JCL.
Closes #3881
Original Pull Request #3883
2021-11-16 14:25:18 +01:00
Jens Schauder
0c37a20a0b After release cleanups.
See #3865
2021-11-12 10:59:43 +01:00
Jens Schauder
230775f98e Prepare next development iteration.
See #3865
2021-11-12 10:59:41 +01:00
Jens Schauder
b28da2eed3 Release version 3.3 GA (2021.1.0).
See #3865
2021-11-12 10:49:36 +01:00
Jens Schauder
02de914993 Prepare 3.3 GA (2021.1.0).
See #3865
2021-11-12 10:49:15 +01:00
Christoph Strobl
5b498f809e Upgrade to MongoDB 4.4.0 Drivers.
Closes: #3875
2021-11-12 07:23:57 +01:00
Mark Paluch
f94a7ee742 After release cleanups.
See #3829
2021-10-18 13:55:41 +02:00
Mark Paluch
ab0ffab488 Prepare next development iteration.
See #3829
2021-10-18 13:55:38 +02:00
Mark Paluch
85b47d66f1 Release version 3.3 RC1 (2021.1.0).
See #3829
2021-10-18 13:48:13 +02:00
Mark Paluch
0d8fe46f3b Prepare 3.3 RC1 (2021.1.0).
See #3829
2021-10-18 13:47:46 +02:00
Christoph Strobl
0bc78f99dd Upgrade to MongoDB 4.4.0-beta1 Drivers.
Closes: #3860
2021-10-14 16:21:32 +02:00
Mark Paluch
e4f450f667 Upgrade to Maven Wrapper 3.8.3.
See #3859
2021-10-11 14:30:24 +02:00
Mark Paluch
49cd44295c Add support for fluent Querydsl and Query by Example query definition.
We now support the functional fluent query definition API for imperative and reactive usage with Querydsl and Query by Example.

Page<PersonProjection> first = repository.findBy(Example.of(probe),
		it -> it.as(PersonProjection.class).project("firstname").page(PageRequest.of(0, 1, Sort.by("firstname"))));

Closes #3757
Original pull request: #3788.
2021-10-08 11:37:26 +02:00
Mark Paluch
767d97a831 Polishing.
Remove code duplications. Reuse target type computation for enum types. Refine method names.

See #3766
Closes #3837
2021-10-07 15:57:08 +02:00
Christoph Strobl
bbe8410979 Render items for collection-like properties when deriving $jsonSchema.
Closes #3766
Original pull request: #3837.
2021-10-07 15:57:08 +02:00
Mark Paluch
c0a4bdb548 Polishing.
Reformat code.

See #3853
Original pull request: #3856.
2021-10-07 15:23:44 +02:00
Christoph Strobl
673a81af0e Fix query/update document reference computation for non-id properties.
We now consider using the target keyword when computing document references. This fixes an issue where query/update statements had not been rendered correctly for references like { 'name' : ?#{#target} }.

Closes #3853
Original pull request: #3856.
2021-10-07 15:23:29 +02:00
Christoph Strobl
977032620e Upgrade to MongoDB 4.3.3 Drivers.
Closes: #3855
2021-10-06 10:51:12 +02:00
Mark Paluch
c7263e5b11 Polishing.
Reformat code.

See #3847
Original pull request: #3848.
2021-10-05 10:08:33 +02:00
Christoph Strobl
eed9b2470a Fix id conversion when storing document reference.
This commit makes sure that the string to ObjectId conversion when storing document references follows the general conversion rules.

Closes #3847
Original pull request: #3848.
2021-10-05 10:08:19 +02:00
Mark Paluch
c350be1f52 Polishing.
Reformat code.

See #3842
Original pull request: #3844.
2021-10-05 09:42:25 +02:00
Christoph Strobl
65b058ffd9 Fix SpEL evaluation in document reference lookup.
Closes #3842
Original pull request: #3844.
2021-10-05 09:42:19 +02:00
Christoph Strobl
4a5789d67e DocumentReference should consider Reference annotations.
Closes #3851
Original pull request: #3852.
2021-10-04 14:30:40 +02:00
Christoph Strobl
7b05cfad94 Update readme.
Shorten MongoDB setup section and add missing anchors.

Original Pull Request: #3833
2021-10-04 10:43:58 +02:00
John Blum
a16a9fe1fe Edit README to include complete steps for building from source.
Closes: #3833
2021-10-04 10:43:04 +02:00
Christoph Strobl
2f98a6656b Fix javadoc errors and warnings
Closes: #3835
2021-09-27 11:13:08 +02:00
Christoph Strobl
9e2f6055a3 Refine CI job triggers.
See #3696
Original pull request: #3753.
2021-09-21 15:20:36 +02:00
Mark Paluch
7f58538292 Use HTTPS in Dockerfiles for package download.
See #3696
Original pull request: #3753.
2021-09-21 15:20:31 +02:00
Christoph Strobl
2f208d712c Update CI to cover MongoDB Server 5.0.
MongoDB has alpha releases in a slightly different location on their distribution server. And they use different keys for signing these alpha releases compared to the overall package listing.

Closes #3696
Original pull request: #3753.
2021-09-21 15:20:26 +02:00
Christoph Strobl
63d9875576 Update test for MongoDB Server 5.0.
Update assertions for changed return types, add a bit of think time and disable tests for no longer supported features.

See #3696
Original pull request: #3753.
2021-09-21 15:20:01 +02:00
Mark Paluch
b7ffff4769 After release cleanups.
See #3771
2021-09-17 09:52:21 +02:00
Mark Paluch
715ae26f3c Prepare next development iteration.
See #3771
2021-09-17 09:52:18 +02:00
Mark Paluch
00350edd32 Release version 3.3 M3 (2021.1.0).
See #3771
2021-09-17 09:44:56 +02:00
Mark Paluch
38e1d0d92d Prepare 3.3 M3 (2021.1.0).
See #3771
2021-09-17 09:44:34 +02:00
Christoph Strobl
8f00ffd291 Change visibility of PersistentEntitiesFactoryBean.
Closes: #3825
2021-09-15 15:30:30 +02:00
Mark Paluch
0af8d6839e Polishing.
Reformat code, fix ticket references in tests.

See #3820
Original pull request: #3821.
2021-09-14 09:12:21 +02:00
Christoph Strobl
9b02897db5 Add configuration support for MongoDB ServerApiVersion.
Introduce FactoryBean and required options to set the ServerAPI.
Update namespace xsd and parsing.

Closes: #3820
Original pull request: #3821.
2021-09-14 09:12:09 +02:00
Christoph Strobl
99203b397a Add support for deriving json schema for encrypted properties.
This commit introduces support for creating a MongoJsonSchema containing encrypted fields for a given type based on mapping metadata.
Using the Encrypted annotation allows to derive required encryptMetadata and encrypt properties within a given (mapping)context.

@Document
@Encrypted(keyId = "...")
static class Patient {

    // ...

    @Encrypted(algorithm = "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic")
    private Integer ssn;

}

MongoJsonSchemaCreator schemaCreator = MongoJsonSchemaCreator.create(mappingContext);
MongoJsonSchema patientSchema = schemaCreator
    .filter(MongoJsonSchemaCreator.encryptedOnly())
    .createSchemaFor(Patient.class);

Closes: #3800
Original pull request: #3801.
2021-09-14 08:56:53 +02:00
Christoph Strobl
eda1c79315 Move and add tests to UpdateMapper.
Also update author information.

Original Pull Request: #3815
2021-09-13 14:26:46 +02:00
divyajnu08
e7150f525e Fix update mapping using nested integer keys on map structures.
Closes: #3775
Original Pull Request: #3815
2021-09-13 14:26:12 +02:00
Mark Paluch
7d6b5ae5fe Upgrade to Maven Wrapper 3.8.2.
See #3818
2021-09-10 15:37:59 +02:00
Christoph Strobl
d70e459ffe Upgrade to MongoDB Java Drivers 4.3.2
Closes: #3816
2021-09-10 10:48:22 +02:00
Mark Paluch
a26e780957 Reduce allocations in query and update mapping.
Introduce EmptyDocument and utility methods in BsonUtils. Avoid entrySet and iterator creation for document iterations/inspections.

Relates to: #3760
Original Pull Request: #3809
2021-09-09 08:00:07 +02:00
Mark Paluch
8fb0e1326b Introduce SessionSynchronization.NEVER to disable transactional participation.
SessionSynchronization.NEVER bypasses all transactional integration in cases where applications do not want to make use of transactions so that transaction inspection overhead is avoided.

Closes: #3760
Original Pull Request: #3809
2021-09-09 07:58:34 +02:00
Christoph Strobl
9014f770d8 Fix slice argument in query fields projection.
We now use a Collection instead of an Array to pass on $slice projection values for offset and limit.

Closes: #3811
Original pull request: #3812.
2021-09-08 14:46:31 +02:00
Christoph Strobl
f128e6df15 Fix @DocumentReference resolution for properties used in constructor.
This commit fixes an issue that prevented referenced entities from being used as constructor arguments.

Closes: #3806
Original pull request: #3810.
2021-09-08 14:35:43 +02:00
Mark Paluch
270456ed81 Polishing.
Extract query that yields no hits into constant. Guard Map-typed reference properties against empty $or.

See #3805
Original pull request: #3807.
2021-09-08 14:18:35 +02:00
Christoph Strobl
4e960a9682 Fix document reference on empty reference arrays.
This commit fixes an issue caused by empty reference arrays.

Closes #3805
Original pull request: #3807.
2021-09-08 14:18:30 +02:00
Mark Paluch
061c28f84a Polishing.
Add ticket reference to tests.

See #3803
2021-09-08 13:59:11 +02:00
Oliver Drotbohm
cba7eaba4c Polishing.
Formatting and indentation in parent project's pom.xml.

See #3803
2021-09-08 13:59:06 +02:00
Oliver Drotbohm
ada7e199a4 Properly detect all supported identifier annotations as explicitly annotated.
We now simply delegate to AnnotationBasedPersistentProperty.isIdProperty() for the detection of annotated identifiers. The previous, manual identifier check was preventing additional identifier annotations, supported by ABP, to be considered, too.

Fixes #3803.
2021-09-08 13:56:49 +02:00
Mark Paluch
977e5e4c5c Polishing.
Tweak reference documentation wording. Extract self/target source dereferencing into utility methods.

See: #3798
Original pull request: #3802.
2021-09-08 13:53:03 +02:00
Christoph Strobl
c8307d5a39 Allow one-to-many style lookups with via @DocumentReference.
This commit adds support for relational style One-To-Many references using a combination of ReadonlyProperty and @DocumentReference.
It allows to link types without explicitly storing the linking values within the document itself.

@Document
class Publisher {

  @Id
  ObjectId id;
  // ...

  @ReadOnlyProperty
  @DocumentReference(lookup="{'publisherId':?#{#self._id} }")
  List<Book> books;
}

Closes: #3798
Original pull request: #3802.
2021-09-08 13:52:46 +02:00
Mark Paluch
dcf184888e Polishing.
Add since and author tags. Update reference docs. Fix format of ticket references in tests.

See #3708
Original pull request: #3796.
2021-09-07 09:56:47 +02:00
divyajnu08
59d0042d13 Add support for $asin and $asinh aggregation operators.
Closes #3708
Original pull request: #3796.
2021-09-07 09:56:30 +02:00
Mark Paluch
8af904b81f Polishing.
Add author and since tags. Tweak Javadoc format.

See #3709
Original pull request: #3794.
2021-09-06 15:50:58 +02:00
divya srivastava
ffceed8da9 Add support for $atan, $atan2 and $atanh aggregation operators.
Closes #3709
Original pull request: #3794.
2021-09-06 15:50:44 +02:00
Mark Paluch
34d66a276a Polishing.
Add license headers. Update Javadoc, author, and since tags. Add tests. Add toCriteriaDefinition method.

See #3790
2021-09-06 15:08:18 +02:00
divyajnu08
e71ec874ab Add support for $expr operator.
Also, allow construction of $match with an AggregationExpression.

Closes #3790
2021-09-06 15:07:06 +02:00
Mark Paluch
f24e8e5361 Avoid nested Document conversion to primitive types for fields with an explicit write target.
We now no longer attempt to convert query Documents into primitive types to avoid e.g. Document to String conversion.

Closes: #3783
Original Pull Request: #3797
2021-09-02 09:50:37 +02:00
Christoph Strobl
bf86f39b2d Fix id field target type conversion for document references.
This commit fixes an issue where a defined custom target type conversion for the id field was not properly considered when writing a document reference.  Previously an eg. String was not being converted into an ObjectId correctly causing lookup queries to return empty results.
Converting the id property value on write solves the issue.
Includes a minor polish in the mapping centralizing pointer creation within the DocumentPointerFactory.

Closes: #3782
Original pull request: #3785.
2021-08-27 09:40:11 +02:00
Mark Paluch
f662d7ca0d Polishing.
Tweak Javadoc. Add since tag, reformat code. Simplify tests. Move documentation bits into the right place.

See #3726.
Original pull request: #3765.
2021-08-27 09:35:33 +02:00
James McNee
62eb719b1e Add support for $sampleRate criteria.
Closes #3726
Original pull request: #3765.
2021-08-27 09:35:12 +02:00
Mark Paluch
69b582823a Polishing.
Add support for Pattern. Extract Regex flags translation from Criteria into RegexFlags utility class. Add since and author tags. Simplify tests. Update reference documentation.

See #3725.
Original pull request: #3781.
2021-08-27 08:47:20 +02:00
divya srivastava
297ef98239 Add support for $regexFind, $regexFindAll, and $regexMatch aggregation operators.
Closes #3725
Original pull request: #3781.
2021-08-26 12:21:55 +02:00
Mark Paluch
f71f107445 Polishing.
Reorder methods. Add since tag. Simplify assertions. Use diamond syntax.

See: #3776
Original pull request: #3777.
2021-08-25 14:58:00 +02:00
Ivan Volzhev
36e2d80d71 Relax requirement for GeoJsonMultiPoint construction allowing creation using a single point.
Only 1 point is required per GeoJson RFC and Mongo works just fine with 1 point as well.

Closes #3776
Original pull request: #3777.
2021-08-25 14:57:08 +02:00
Mark Paluch
467536cb34 Polishing.
Update since version. Reformat code.

See: #3761.
2021-08-25 14:33:36 +02:00
sangyongchoi
302c8031f9 Add Criteria infix functions for maxDistance and minDistance.
Closes: #3761
2021-08-25 14:33:10 +02:00
Mark Paluch
7c6e951c7c Polishing.
Add author tags, tweak Javadoc style. Simplify tests. Document operator.

See #3724
Original pull request: #3759.
2021-08-25 11:13:02 +02:00
Mushtaq Ahmed
92cc2a582a Add support for $rand aggregation operator.
Closes #3724
Original pull request: #3759
2021-08-25 11:08:16 +02:00
Mark Paluch
24171b3ae2 Polishing.
Introduce factory methods to convert TimeZone/ZoneId/ZoneOffset into Mongo Timezone. Introduce TemporalUnit abstraction and converters to convert ChronoUnit and TimeUnit into TemporalUnit for date operators accepting a unit parameter.

See #3713
Original pull request: #3748.
2021-08-25 11:01:34 +02:00
Christoph Strobl
456c1ad26a Add shortcut for date aggregation operators working with timezone.
See: #3713
Original pull request: #3748.
2021-08-25 11:01:27 +02:00
Christoph Strobl
fc41793d5d Add support for $dateDiff aggregation operator.
Closes: #3713
Original pull request: #3748.
2021-08-25 11:01:17 +02:00
Christoph Strobl
afef243634 Add support for $dateAdd aggregation operator.
Closes: #3713
Original pull request: #3748.
2021-08-25 11:01:00 +02:00
Mark Paluch
869b88702d Polishing.
Fix typo in reference docs.

See #3758
2021-08-25 10:15:13 +02:00
Ryan Gibb
aca403c112 Fix a typo in MongoConverter javadoc.
Original pull request: #3758.
2021-08-25 10:14:20 +02:00
Mark Paluch
df0372eee1 Polishing.
Rename AngularDimension to AngularUnit. Tweak Javadoc. Simplify tests. Update reference docs.

See: #3710, #3714, #3728, #3730
Original pull request: #3755.
2021-08-24 16:18:17 +02:00
Christoph Strobl
c4c6267d91 Add support for $cos and $cosh aggregation operators.
Closes: #3710
Original pull request: #3755.
2021-08-24 16:18:17 +02:00
Christoph Strobl
73d5886aae Add support for $tan and $tanh aggregation operators.
Closes: #3730
Original pull request: #3755.
2021-08-24 16:18:17 +02:00
Christoph Strobl
0db47169cf Add support for $sin and $sinh aggregation operators.
Closes: #3728
Original pull request: #3755.
2021-08-24 16:18:14 +02:00
Christoph Strobl
ec16b873b7 Add support for $degreesToRadians aggregation operator.
Closes: #3714
Original pull request: #3755.
2021-08-24 16:16:01 +02:00
Mark Paluch
2a3a4cf030 Polishing.
Fix method order from earlier merges. Add missing Javadoc. Simplify tests. Update documentation.

See #3721
Original pull request: #3746.
2021-08-24 15:01:54 +02:00
Christoph Strobl
df2b2a2f68 Add support for $integral aggregation operator.
Closes: #3721
Original pull request: #3746.
2021-08-24 15:01:49 +02:00
Mark Paluch
fd0a402c99 Polishing.
See #3720
Original pull request: #3745.
2021-08-24 14:34:43 +02:00
Christoph Strobl
6bd0f758fe Extend support for $ifNull to cover multiple conditions.
Closes: #3720
Original pull request: #3745.
2021-08-24 14:34:43 +02:00
Mark Paluch
10c0203605 Polishing.
Accept window units in addition to plain strings. Document operator.

See: #3716
Original pull request: #3742.
2021-08-24 14:30:52 +02:00
Christoph Strobl
82b33331fc Add support for $derivative aggregation operator.
Closes: #3716
Original pull request: #3742.
2021-08-24 14:30:52 +02:00
Mark Paluch
75b5a548b6 Polishing.
Fix asterisk callouts.

See #3786
2021-08-24 11:23:42 +02:00
Mark Paluch
0c481feb72 Extract Aggregation Framework and GridFS docs in own source files.
Closes #3786
2021-08-24 11:09:06 +02:00
Mark Paluch
c8a791d367 Polishing.
Make fields final where possible. Update javadoc. Simplify assertions. Update reference docs.

See: #3715, See #3717, See #3727
Original pull request: #3741.
2021-08-24 11:07:40 +02:00
Christoph Strobl
510028a834 Add support for $shift aggregation Operator.
Closes: #3727
Original pull request: #3741.
2021-08-24 11:07:31 +02:00
Christoph Strobl
1a86761e2e Add support for $documentNumber aggregation operator.
Closes: #3717
Original pull request: #3741.
2021-08-24 11:07:22 +02:00
Christoph Strobl
30da62181f Add support for $rank and $denseRank aggregation operators.
Closes: #3715
Original pull request: #3741.
2021-08-24 11:06:59 +02:00
Christoph Strobl
a977b8a790 Change visibility of Reactive/MongoRepositoryFactoryBean setters.
Setters of the FactoryBean should be public.

Closes: #3779
Original pull request: #3780.
2021-08-24 10:26:44 +02:00
Christoph Strobl
f3e067f59f Add support for $expMovingAvg aggregation operator.
The SpEL support for this one is missing due to the differing argument map (N, alpha).

Closes: #3718
Original pull request: #3744.
2021-08-23 14:44:14 +02:00
Christoph Strobl
dbfd4e5c62 Polishing.
Reformat code.

See #3712
Original pull request: #3740.
2021-08-23 14:29:16 +02:00
Christoph Strobl
c574e5cf8a Add support for $covariancePop and $covarianceSamp aggregation expressions.
Closes: #3712
Original pull request: #3740.
2021-08-23 14:25:41 +02:00
Mark Paluch
f9f4c4621b Polishing.
Update javadoc and add assertions.

See #3711
Original pull request: #3739.
2021-08-23 11:21:35 +02:00
Christoph Strobl
23254c10dc Add support for $setWindowFields aggregation stage.
Add a SetWindowFieldsOperation to the aggregation framework.

The builder API allows fluent declaration of the aggregation stage as shown in the sample below.

SetWindowFieldsOperation.builder()
	.partitionByField("state")
	.sortBy(Sort.by(Direction.ASC, "date"))
	.output(AccumulatorOperators.valueOf("qty").sum())
	.within(Windows.documents().fromUnbounded().toCurrent().build())
	.as("cumulativeQuantityForState")
	.build();

Closes #3711
Original pull request: #3739.
2021-08-23 11:21:35 +02:00
Christoph Strobl
255491c446 Upgrade to MongoDB 4.3.1 Drivers.
Closes: #3778
2021-08-23 10:49:22 +02:00
Christoph Strobl
1d943d62a3 Fix build on Java 16.
Make sure to use an initialized MappingContext.

Closes: #3749
Original pull request: #3752.
2021-08-23 10:29:35 +02:00
Jens Schauder
7538b1a1a5 After release cleanups.
See #3736
2021-08-12 15:16:23 +02:00
Jens Schauder
828c074167 Prepare next development iteration.
See #3736
2021-08-12 15:16:21 +02:00
Jens Schauder
87ab1ac48c Release version 3.3 M2 (2021.1.0).
See #3736
2021-08-12 15:03:17 +02:00
Jens Schauder
454afd9877 Prepare 3.3 M2 (2021.1.0).
See #3736
2021-08-12 15:02:56 +02:00
Mark Paluch
45971b212c Polishing.
Move off deprecated classes. Add unpaged testcase for query by example.

Original Pull Request: #3754
2021-07-26 15:16:05 +02:00
Mark Paluch
68370c16fb Run unpaged query using Pageable.unpaged() through QuerydslMongoPredicateExecutor.findAll(…).
We now correctly consider unpaged queries if the Pageable is unpaged.

Closes: #3751
Original Pull Request: #3754
2021-07-26 15:15:37 +02:00
Christoph Strobl
d2c9b47366 Fix issues related to Querydsl 5.0 upgrade.
Remove overridden methods no longer available in public api.

Closes: #3738
2021-07-22 09:03:10 +02:00
Jens Schauder
4d7ee0e741 After release cleanups.
See #3631
2021-07-16 14:19:58 +02:00
Jens Schauder
e7f3a2436d Prepare next development iteration.
See #3631
2021-07-16 14:19:56 +02:00
Jens Schauder
4ef1ff6aff Release version 3.3 M1 (2021.1.0).
See #3631
2021-07-16 14:09:25 +02:00
Jens Schauder
b6ad32d7d4 Prepare 3.3 M1 (2021.1.0).
See #3631
2021-07-16 14:08:59 +02:00
Jens Schauder
e875f9ea33 Updated changelog.
See #3631
2021-07-16 14:08:43 +02:00
Jens Schauder
9db9d16cf8 Updated changelog.
See #3681
2021-07-16 10:48:16 +02:00
Mark Paluch
f00991dc29 Polishing.
Rename Granularities/Granularity to Granularity and GranularityDefinition to proivide a more natural wording towards using predefined granularities.

Validate presence of referenced properties through the TimeSeries annotation.

Tweak Javadoc, reformat code, add unit tests.

See #3731
Original pull request: #3732.
2021-07-16 09:44:43 +02:00
Christoph Strobl
bacbd7133e Add support for creating Time Series collection.
Introduce time series to CollectionOptions and add dedicated TimeSeries annotation to derive values from.

Closes #3731
Original pull request: #3732.
2021-07-16 09:44:35 +02:00
Mark Paluch
f38f6d67ab Polishing.
Support DBObject and Map that as source for entity materialization and map conversion.

See #3702
Original pull request: #3704.
2021-07-15 10:00:33 +02:00
Christoph Strobl
3f27e8e152 Fix raw document conversion in Collection like properties.
Along the lines make sure to convert map like structures correctly if they do not come as a Document, eg. cause they got converted to a plain Map in a post load, pre convert event.

Closes #3702
Original pull request: #3704.
2021-07-15 10:00:31 +02:00
Christoph Strobl
23177fef0c Custom Converter should also be applicable for simple types.
This commit fixes a regression that prevented custom converters from being applied to types considered store native ones.

Original pull request: #3703.
Fixes #3670
2021-07-15 08:54:31 +02:00
Mark Paluch
f3b90c2b8a Polishing.
Reformat code. Tweak javadoc. Reject wildcard projection usage on properties with a MappingException. Omit wildcard projections when declared on document types that are used as subdocument.

See #3225
Original pull request: #3671.
2021-07-14 15:16:00 +02:00
Christoph Strobl
d57c5a9529 Add support for Wildcard Index.
Add WildcardIndexed annotation and the programatic WildcardIndex.

Closes #3225
Original pull request: #3671.
2021-07-14 15:16:00 +02:00
Mark Paluch
986ea39f90 Upgrade to Querydsl 5.0.
Move off our own Querydsl copies, as Querydsl 5.0 ships MongoDB Document API support.
Remove package-private duplicates of Querydsl code.
Introduce SpringDataMongodbQuerySupport to provide a well-formatted toString representation of the actual query.

Original Pull Request: #3674
2021-07-14 10:15:12 +02:00
Christoph Strobl
5bd7ff1413 Upgrade to MongoDB 4.3.0 Drivers.
Closes: #3706
2021-07-14 07:44:00 +02:00
Mark Paluch
93b9f23b07 Polishing.
Fix proxy comparison.

See #3705
2021-07-13 08:42:24 +02:00
Mark Paluch
42ab7d2f63 Adapt to changes in AssertJ 3.20.
Closes #3705
2021-07-13 08:27:51 +02:00
Christoph Strobl
a6a2f0bde9 Upgrade to MongoDB 4.3.0-beta4 Drivers.
Closes: #3693
2021-07-12 14:56:44 +02:00
Oliver Drotbohm
7d0b070d1f Adapt to API consolidation in Spring Data Commons' PersistentProperty.
Closes: #3700
Original Pull Request: #3701
Related to: spring-projects/spring-data-commons#2408
2021-07-12 08:09:26 +02:00
Christoph Strobl
81bc3c599b Disable tests on Java 16 that require class-based proxies.
Original pull request: #3687.
Resolves #3656
2021-07-08 12:08:54 +02:00
Christoph Strobl
403f0019d5 Fix Optional handling in query creation and result processing.
Original pull request: #3687.
Resolves #3656
2021-07-08 12:08:50 +02:00
Christoph Strobl
4f65bb0810 Fix mapping context setup to include simple type holder.
Original pull request: #3687.
Resolves #3656
2021-07-08 12:08:32 +02:00
Christoph Strobl
ef29e69a87 Polishing.
Simplify KeyMapper current property/index setup.

Original Pull Request: #3689
2021-07-06 11:46:35 +02:00
David Julia
5cffb3c07c Fix Regression in generating queries with nested maps with numeric keys.
While maps that have numeric keys work if there is only one map with an integer key, when there are multiple maps with numeric keys in a given query, it fails.

Take the following example for a map called outer with numeric keys holding reference to another object with a map called inner with numeric keys: Updates that are meant to generate {"$set": {"outerMap.1234.inner.5678": "hello"}} are instead generating {"$set": {"outerMap.1234.inner.inner": "hello"}}, repeating the later map property name instead of using the integer key value.

This commit adds unit tests both for the UpdateMapper and QueryMapper, which check multiple consecutive maps with numeric keys, and adds a fix in the KeyMapper. Because we cannot easily change the path parsing to somehow parse path parts corresponding to map keys differently, we address the issue in the KeyMapper. We keep track of the partial path corresponding to the current property and use it to skip adding the duplicated property name for the map to the query, and instead add the key.

This is a bit redundant in that we now have both an iterator and an index-based way of accessing the path parts, but it gets the tests passing and fixes the issue without making a large change to the current approach.

Fixes: #3688
Original Pull Request: #3689
2021-07-06 11:36:11 +02:00
Christoph Strobl
61d3a0bd1f Fix NPE when reading/mapping null value inside collection.
Closes: #3686
2021-07-01 10:50:57 +02:00
Christoph Strobl
82d67c1dbb Favor ObjectUtils over Objects for equals/hashCode.
Original Pull Request: #3684
2021-06-24 13:32:48 +02:00
Gatto
85a30ec915 Add equals and hashCode to UnwrappedMongoPersistentProperty.
Fixes #3683
Original Pull Request: #3684
2021-06-24 13:32:40 +02:00
Mark Paluch
c70c29b2c7 Updated changelog.
See #3650
2021-06-22 16:07:25 +02:00
Mark Paluch
2a5ae0da37 Updated changelog.
See #3649
2021-06-22 15:29:50 +02:00
Mark Paluch
826015e9c1 Update reference docs to use correct MongoClient.
Closes #3666
2021-06-22 14:37:05 +02:00
larsw
9dda0a2f93 Add closing quote to GeoJson javadoc.
Closes #3677
2021-06-21 13:58:07 +02:00
Christoph Strobl
7dfe460433 Fix field projection value conversion.
The field projection conversion should actually only map field names and avoid value conversion. In the MongoId case an inclusion parameter (1) was unintentionally converted into its String representation which causes trouble on Mongo 4.4 servers.

Fixes: #3668
Original pull request: #3678.
2021-06-21 13:45:46 +02:00
Christoph Strobl
73a0f04933 Polishing.
Fix typo in class name and make sure MongoTestTemplate uses the configured simple types.
Remove superfluous junit extension.

See: #3659
Original pull request: #3661.
2021-06-18 14:12:48 +02:00
Christoph Strobl
a1c165921d Fix query mapper path resolution for types considered simple ones.
spring-projects/spring-data-commons#2293 changed how PersistentProperty paths get resolved and considers potentially registered converters for those, which made the path resolution fail in during the query mapping process.
This commit makes sure to capture the according exception and continue with the given user input.

Fixes: #3659
Original pull request: #3661.
2021-06-18 14:12:39 +02:00
Christoph Strobl
3872b379cd Fix $or / $nor keyword mapping in query mapper.
This commit fixes an issue with the pattern used for detecting $or / $nor which also matched other keywords like $floor.

Closes: #3635
Original pull request: #3637.
2021-06-18 13:48:29 +02:00
Mark Paluch
98fe043b95 Directly import JSR305 jar.
Closes #3672
2021-06-17 09:41:46 +02:00
Mark Paluch
c217618d9d Polishing.
Reorder methods and types. Rename MongoPersistentProperty.isOmitNullProperty to writeNullValues. Adapt caching MongoPersistentProperty and add tests.

Tweak Javadoc wording, add author and since tags.

See #3407
Original pull request: #3646.
2021-06-14 11:53:24 +02:00
Divya Srivastava
b1020d19ba Add an option to @Field annotation to include/exclude null values on write.
Properties can be annotated with `@Field(write=…)` to control whether a property with a null value should be included or omitted (default) during conversion in the target Document.

Closes #3407
Original pull request: #3646.
2021-06-14 11:53:09 +02:00
Mark Paluch
a481636429 Polishing.
Add nullability annotation. Return early on null value conversion.

See #3633
Original pull request: #3643.
2021-06-09 14:13:42 +02:00
Christoph Strobl
efa9a2d408 Add Criteria.isNullValue() as alternative to Criteria.is(null).
See #3633
Original pull request: #3643.
2021-06-09 14:13:42 +02:00
Christoph Strobl
149a703ecc Fix NPE in QueryMapper when trying to apply target type on null value.
Closes #3633
Original pull request: #3643.
2021-06-09 14:13:42 +02:00
Mark Paluch
2b715c54d3 Polishing.
Reformat code.

See #3660.
Original pull request: #3662.
2021-06-09 11:33:12 +02:00
Christoph Strobl
ece261aadb Fix conversion for types having a converter registered.
Fixes: #3660
Original pull request: #3662.
2021-06-09 11:33:00 +02:00
Mark Paluch
dae0ac3b4d Remove duplicate LazyLoadingInterceptor code by reusing LazyLoadingProxyFactory.
Original pull request: #3647.
Closes #3602.
2021-05-21 14:20:01 +02:00
Mark Paluch
5ab75eb65a Polishing.
Reduce dependencies in tests by using NoOpDbRefResolver.
Add since tags.

Tweak documentation. Extract entity references into own documentation fragment.

Original pull request: #3647.
Closes #3602.
2021-05-21 14:20:01 +02:00
Christoph Strobl
e96ef8e18f Avoid capturing lambdas, update javadoc and add tests.
Also allow direct usage of (at)Reference from data commons to define associations.

Original pull request: #3647.
Closes #3602.
2021-05-21 14:20:00 +02:00
Mark Paluch
82af678cab Polishing
Rename ReferenceReader to ReferenceLookupDelegate.
Rename LazyLoadingProxyGenerator to LazyLoadingProxyFactory.
Rename DefaultReferenceLoader to MongoDatabaseFactoryReferenceLoader.

Reduce scope of LookupFunction and move it to ReferenceLookupDelegate.

Extract some checks into methods to reflect the underlying concepts. Simplify code, convert variables to constants where possible.

Original pull request: #3647.
Closes #3602.
2021-05-21 14:20:00 +02:00
Christoph Strobl
6ed274bd9b Update entity linking support to derive document pointer from lookup query.
Simplify usage by computing the pointer from the lookup.
Update the reference documentation, add JavaDoc and refine API.

Original pull request: #3647.
Closes #3602.
2021-05-21 14:20:00 +02:00
Mark Paluch
48ac7e75ba First pass of review polishing.
Original pull request: #3647.
Closes #3602.
2021-05-21 14:20:00 +02:00
Christoph Strobl
a51c96298f Enhance support for linking entities.
Add initial support for an alternative to the existing DBRef scenario.
The enhancement allows to store and retrieve linked entites via their id or a customizable lookup query.

Original pull request: #3647.
Closes #3602.
2021-05-21 14:20:00 +02:00
Mark Paluch
f1354c4508 Revise DocumentCallback nullability constraints.
DocumentCallback is now generally non-nullable for both, the input Document and the returned result expecting EntityReader to always return a non-null object.

Also, use try-with-resources where applicable.

Closes #3648
2021-05-18 15:11:06 +02:00
Mark Paluch
ff7588f648 Updated changelog.
See #3629
2021-05-14 12:36:34 +02:00
Mark Paluch
124036fe36 Updated changelog.
See #3628
2021-05-14 12:06:37 +02:00
Greg L. Turnquist
80c5b536df Polishing. 2021-05-13 16:15:04 -05:00
Greg L. Turnquist
2ee33b1444 Polishing. 2021-05-13 15:56:39 -05:00
Greg L. Turnquist
eec6cea507 Update CI to JDK 16.
See #3603.
2021-05-13 15:52:30 -05:00
Mark Paluch
90d03d92d8 Polishing.
Let appendLimitAndOffsetIfPresent accept unary operators for adjusting limit/offset values instead of appendModifiedLimitAndOffsetIfPresent. Apply simple type extraction for Slice. Add support for aggregation result streaming.

Extend tests, add author tags, update docs.

See #3543.
Original pull request: #3645.
2021-05-11 11:50:40 +02:00
divya_jnu08
9a48e32565 Aggregation query method should be able to return Slice and Stream.
Aggregation query methods can not return Slice and Stream.

interface PersonRepository extends CrudReppsitory<Person, String> {

  @Aggregation("{ $group: { _id : $lastname, names : { $addToSet : ?0 } } }")
  Slice<PersonAggregate> groupByLastnameAnd(String property, Pageable page);

  @Aggregation("{ $group: { _id : $lastname, names : { $addToSet : $firstname } } }")
  Stream<PersonAggregate> groupByLastnameAndFirstnamesAsStream();
}

Closes #3543.
Original pull request: #3645.
2021-05-11 11:50:10 +02:00
Mark Paluch
ede6927b65 Introduce template method for easier customization of fragments.
Closes #3638.
2021-04-27 10:45:43 +02:00
Greg L. Turnquist
2edc29f758 Authenticate with artifactory.
See #3616.
2021-04-22 14:59:20 -05:00
Clément Petit
5bd9bcca75 Fix bullet points in aggregation framework reference documentation.
Closes: #3632
2021-04-20 08:19:46 +02:00
Greg L. Turnquist
54f75e653b Migrate to main branch.
See #3616.
2021-04-16 12:27:26 -05:00
Mark Paluch
7b33f56e33 After release cleanups.
See #3616
2021-04-14 14:30:14 +02:00
Mark Paluch
829eed7d6c Prepare next development iteration.
See #3616
2021-04-14 14:30:11 +02:00
Mark Paluch
5d3a3e1fe2 Release version 3.2 GA (2021.0.0).
See #3616
2021-04-14 14:18:47 +02:00
Mark Paluch
e71ec4fc41 Prepare 3.2 GA (2021.0.0).
See #3616
2021-04-14 14:18:21 +02:00
Mark Paluch
f065e295e9 Updated changelog.
See #3616
2021-04-14 14:18:16 +02:00
Mark Paluch
d23e1b3247 Updated changelog.
See #3617
2021-04-14 11:43:30 +02:00
Mark Paluch
a1e8e6f3bc Updated changelog.
See #3597
2021-04-14 11:17:39 +02:00
Mark Paluch
e4030197e8 Polishing.
Fix nullability annotations for isEqual(…) parameters. Fix generics. Reformat code.

Add tests.

See #3414
Original pull request: #3615.
2021-04-13 09:39:33 +02:00
Clement Petit
2885c35511 Handle nested Pattern and Document in Criteria.equals(…).
Closes #3414
Original pull request: #3615.
2021-04-13 09:39:16 +02:00
Mark Paluch
a2a33390b6 Polishing.
Use ObjectUtils for empty check.

See #3623
Original pull request: #3625.
2021-04-13 09:09:33 +02:00
Christoph Strobl
bf606bcc47 Fix NPE in declarative aggregation execution.
This commit fixes an issue where using a simple return type leads to NPE when the actual aggregation result does not contain any values.

Closes: #3623
Original pull request: #3625.
2021-04-13 09:09:29 +02:00
Christoph Strobl
e91809957d Upgrade to MongoDB Java Drivers 4.2.3
Closes: #3621
2021-04-09 12:49:47 +02:00
Christoph Strobl
313a7b86e8 Fix query mapping resolution of properties using underscore within field name.
Closes: #3601
Original pull request: #3607.
2021-04-09 12:26:01 +02:00
Mark Paluch
9d7473487f Upgrade to MongoDB 4.4 on CI.
Closes #3612.
2021-04-08 17:13:49 +02:00
Mark Paluch
2734a7d8d4 Guard tests against unsupported MongoDB versions used for tests.
See #3583
2021-04-08 16:13:13 +02:00
Mark Paluch
0f85808531 Updated changelog.
See #3598
2021-03-31 18:30:43 +02:00
Mark Paluch
7c0afda0a6 After release cleanups.
See #3595
2021-03-31 17:24:05 +02:00
Mark Paluch
dbe17249b7 Prepare next development iteration.
See #3595
2021-03-31 17:24:03 +02:00
Mark Paluch
cfe0baadd1 Release version 3.2 RC1 (2021.0.0).
See #3595
2021-03-31 17:05:07 +02:00
Mark Paluch
8d0143ad76 Prepare 3.2 RC1 (2021.0.0).
See #3595
2021-03-31 17:04:34 +02:00
Mark Paluch
43fee26950 Updated changelog.
See #3595
2021-03-31 17:04:28 +02:00
Mark Paluch
70145a4c86 Use StringUtils.replace(…) instead of String.replaceAll(…) for mapKeyDotReplacement.
We now use StringUtils.replace(…) to replace the map key dot in MappingMongoConverter. StringUtils perform a plain search instead of using Regex which improves the overall performance.

Closes #3613
2021-03-30 14:29:44 +02:00
Mark Paluch
f7a90e93c5 Polishing.
Omit StreamUtils usage if input is a collection. Remove superfluous Flux.from(…). Simplify test and migrate test to JUnit 5.

See #3609.
Original pull request: #3611.
2021-03-29 10:55:29 +02:00
Clément Petit
3e78ce212a Return saved entity reference instead of original reference.
Make SimpleReactiveMongoRepository#saveAll(Publisher<S>) return the saved entity references instead of the original references.

Closes #3609
Original pull request: #3611.
2021-03-29 10:55:20 +02:00
Christoph Strobl
5a87dec2d5 Rename Embedded annotation to Unwrapped.
The meaning of embedding a Document in MongoDB is different compared to column based stores. Typically the term is used for a Document in Document approach and not for flattening out a values into the enclosing Document.

Closes: #3600
Original pull request: #3604.
2021-03-26 14:42:27 +01:00
Mark Paluch
f4556406bd Polishing.
Reorder methods. Tweak Javadoc and documentation wording. Mention projection expressions in the what's new section. Reformat code.

See #3583
Original pull request: #3585.
2021-03-18 12:09:09 +01:00
Christoph Strobl
af6d1eff0c Support expressions in query field projections.
// explicit via dedicated AggregationExpression
query.fields()
  .project(StringOperators.valueOf("name").toUpper())
  .as("name");

// with a user provided expression parsed from a String
query.fields().project(MongoExpression.create("'$toUpper' : '$name'"))
  .as("name")

// using SpEL support
query.fields().project(AggregationSpELExpression.expressionOf("toUpper(name)"))
  .as("name");

// with parameter binding
query.fields().project(
    MongoExpression.create("'$toUpper' : '?0'").bind("$name")
  ).as("name")

// via the @Query annotation on repositories
@Query(value = "{ 'id' : ?0 }", fields = "{ 'name': { '$toUpper': '$name' } }")

Closes: #3583
Original pull request: #3585.
2021-03-18 12:03:30 +01:00
Mark Paluch
191993caef After release cleanups.
See #3558
2021-03-17 11:30:30 +01:00
Mark Paluch
dbed948c73 Prepare next development iteration.
See #3558
2021-03-17 11:30:28 +01:00
Mark Paluch
8f232e4983 Release version 3.2 M5 (2021.0.0).
See #3558
2021-03-17 11:17:49 +01:00
Mark Paluch
e961d3c995 Prepare 3.2 M5 (2021.0.0).
See #3558
2021-03-17 11:17:26 +01:00
Mark Paluch
699d5f40f5 Updated changelog.
See #3558
2021-03-17 11:17:23 +01:00
Mark Paluch
4b58ecc041 Updated changelog.
See #3561
2021-03-17 11:03:38 +01:00
Mark Paluch
4b8fb812fa Updated changelog.
See #3556
2021-03-17 10:35:11 +01:00
Mark Paluch
78137c882d Polishing.
Move hasValue(…) from DocumentAccessor to BsonUtils. Fix typo in tests.

See: #3590
Original pull request: #3591.
2021-03-15 14:02:02 +01:00
Christoph Strobl
8033b05cb7 Fix ShardKey lookup for nested paths.
This commit fixes the lookup of shard key values for nested paths using the dot (.) notation.

Closes: #3590
Original pull request: #3591.
2021-03-15 14:01:49 +01:00
Christoph Strobl
a1a0675976 Fix CustomConverter conversion lookup.
This commit makes sure to fall back to the configured custom converter if no more type specific converter has been registered.

Closes #3580
Original pull request: #3581.
2021-03-15 13:22:16 +01:00
Mark Paluch
a88748d798 Remove @Persistent from entity-scan include filters.
We now only scan for entities annotated with `@Document` to avoid inclusion of non-MongoDB entities. Previously, types annotated (or meta-annotated) with `@Persistent` were included as MongoDB entity which could lead to mapping rule violations.

Closes #3592
2021-03-11 15:07:56 +01:00
Christoph Strobl
c2fc09e324 Upgrade to MongoDB Java Drivers 4.2.2
Closes #3579
2021-03-03 11:26:32 +01:00
Christoph Strobl
be8e70225a Remove duplicate code in MappingMongoConverter.
Also remove MapUtils and blend new methods into the existing BsonUtils.

Original Pull Request: #3575
2021-03-03 11:26:24 +01:00
Mark Paluch
92079ca200 Introduce ConversionContext.
Introduce a ConversionContext used during the mapping process to carry forward required information.
ConversionContext serves as entrpoint for recursive (read) conversion of documents, lists, maps, and simple values. The actual decision which converter strategy to apply is now encapsulated by ConversionContext.convert(…) which removes strategy duplications from the actual conversion methods.

Also, converter methods for documents, maps, lists, … are now protected for easier customization by subclasses.

Closes #3571
Original Pull Request: #3575
2021-03-03 10:16:10 +01:00
Christoph Strobl
52b13ccf58 Preserve class keyword as Map key during update mapping.
This commit makes sure to skip the class property ob Object when mapping maps and their keys inside an Update.

Closes #3566
Original pull request: #3577.
2021-03-02 11:38:24 +01:00
Mark Paluch
d73c2e3602 Polishing.
Reformat code. Reduce method visibility in JUnit 5 tests. Add Nullable annotations to address warnings.

See #3568
Original pull request: #3569.
2021-03-02 11:30:15 +01:00
Brice Vandeputte
39e301d98d Translate MongoSocketException subclasses to DataAccessResourceFailureException.
Closes #3568
Original pull request: #3569.
2021-03-02 11:30:12 +01:00
Mark Paluch
a7d865eb5e Polishing.
Update Javadoc.

Closes #3570.
Original pull request: #3576.
2021-03-02 11:18:06 +01:00
Christoph Strobl
cde39008cf Assert MongoTemplate rejects saving collection like entities like Lists or Iterator.
Closes #3570.
Original pull request: #3576.
2021-03-02 11:18:04 +01:00
Christoph Strobl
ffaa7cae6f Remove duplicate JSON Schema section from reference documentation.
Closes: #3573
Original pull request: #3574.
2021-03-01 14:42:07 +01:00
Christoph Strobl
2ef9844219 Move collection like check for reactive-/template insert methods to EntityOperations.
Reintroduce the protected ensureNotIterable method in MongoTemplate to keep the API stable. Delegate to the newly introduced method and move the collection like check to EntityOperations.

Original Pull Request: #590
2021-02-22 11:10:06 +01:00
GotoFinal
6f13837890 Update ensureNotIterable check for inserts.
Check if an object is an array or is an instance of collection or iterator instead of checking against collection names which is likely to never work.

Closes #2911
Original Pull Request: #590
2021-02-22 10:44:47 +01:00
Mark Paluch
1ca2f5c3f1 Polishing.
Simplify assertions.

See #3552.
Original pull request: #3565.
2021-02-22 09:56:21 +01:00
Christoph Strobl
a5e209379c Preserve numeric keys that exceed Long range when mapping Updates.
This commit makes sure we preserve map keys no matter what.

Closes #3552.
Original pull request: #3565.
2021-02-22 09:56:12 +01:00
Mark Paluch
bcb5628840 Polishing.
Update javadoc, add since tags. Add non-null assertions. Introduce overload for type(…) accepting a collection

See #3286.
Original pull request: #811.
2021-02-19 10:28:33 +01:00
Ziemowit Stolarczyk
0b27635d67 Add possibility to use Collection<Criteria> as parameter in and/or/nor operators.
Closes #3286.
Original pull request: #811.
2021-02-19 10:28:23 +01:00
Mark Paluch
198ebaa7d8 Polishing.
Reformat code. Add since tags.

See #3395
Original pull request: #3554.
2021-02-18 15:08:29 +01:00
Christoph Strobl
bebb1b6ce4 Fix case insensitive derived in queries on String properties.
We now consider the IgnoreCase part of a derived query when used along with In. Strings will be quoted to avoid malicious strings from being handed over to the server as a regular expression to evaluate.

See #3395
Original pull request: #3554.
2021-02-18 15:08:26 +01:00
Christoph Strobl
f59a38575a After release cleanups.
See #3560
2021-02-18 11:35:22 +01:00
Christoph Strobl
da70b34f13 Prepare next development iteration.
See #3560
2021-02-18 11:35:20 +01:00
Christoph Strobl
f4f24ec1a7 Release version 3.2 M4 (2021.0.0).
See #3560
2021-02-18 11:25:13 +01:00
Christoph Strobl
f1365c5c55 Prepare 3.2 M4 (2021.0.0).
See #3560
2021-02-18 11:24:46 +01:00
Christoph Strobl
71364255ca Updated changelog.
See #3560
2021-02-18 11:24:41 +01:00
Christoph Strobl
22952c3ef0 Updated changelog.
See #3557
2021-02-18 11:18:24 +01:00
Christoph Strobl
27b3b604c9 After release cleanups.
See #3537
2021-02-17 14:17:49 +01:00
Christoph Strobl
bce280d02b Prepare next development iteration.
See #3537
2021-02-17 14:17:47 +01:00
Christoph Strobl
4b6ab894bf Release version 3.2 M3 (2021.0.0).
See #3537
2021-02-17 14:00:09 +01:00
Christoph Strobl
38c1d7fc37 Prepare 3.2 M3 (2021.0.0).
See #3537
2021-02-17 13:59:43 +01:00
Christoph Strobl
43bef87966 Updated changelog.
See #3537
2021-02-17 13:59:28 +01:00
Christoph Strobl
c2498d41a1 Updated changelog.
See #3536
2021-02-17 13:49:15 +01:00
Christoph Strobl
c4182262ce Updated changelog.
See #3520
2021-02-17 11:34:20 +01:00
Christoph Strobl
3149c6e35b Updated changelog.
See #3519
2021-02-17 10:58:20 +01:00
Christoph Strobl
6d662461b8 Polishing.
Reduce method visibility in tests, enable missed test and format code.

Closes #3546.
Original pull request: #3551.
2021-02-17 07:41:12 +01:00
Christoph Strobl
597d6825f7 Use UUID toString representation when converting org.bson.Document into a json String.
This commit switches the rendering of UUID values to their toString format when printing org.bson.Document to json via the DocumentToString converter.

This will move the resulting representation from {"$binary": "QUK3ZihZ9cdhWjTf5TZqrw==", "$type": "03"} to 480971b0-7160-4120-acd0-6fd6b82418ad which is the more natural variant within Java applications.

The conversion only applies on read in cases where an entire document eg. a composite id, is mapped to a String property of the domain model.

Closes #3546.
Original pull request: #3551.
2021-02-17 07:41:11 +01:00
Christoph Strobl
8b060455c2 Fix DocumentToStringConverter UUID representation when calling toJson.
This commit makes sure to use an Encoder having UuidRepresentation set when calling org.bson.Document#toJson, preventing CodecConfigurationException from being raised.

Future versions will make sure the UUID string representation matches the Java default one.

Closes #3546.
Original pull request: #3551.
2021-02-17 07:41:11 +01:00
Christoph Strobl
2bf60ac827 Upgrade MongoDB drivers to 4.2.0.
Closes #3553
2021-02-16 15:48:01 +01:00
Mark Paluch
f3d6f405c9 Polishing.
Reorder API methods, remove unused MongoPersistentProperty.isNullable method, reduce visibility where possible. Add Javadoc and tweak documentation wording.

Introduce DotPath utility to abstract dot path concatenation.

See #2803.
Original pull request: #896.
2021-02-16 14:45:24 +01:00
Christoph Strobl
bd985a6589 Add support for embedded types.
We now support embedded types in the sense of unwrapping nested objects into their parent Document to flatten out domain models where needed.

A domain class of:

public class User {
    @Id
    private String userId;

    @Embedded(onEmpty = USE_NULL)
    private UserName name;
}

public class UserName {
    private String firstname;
    private String lastname;
}

renders:

{
  "_id" : "1da2ba06-3ba7",
  "firstname" : "Emma",
  "lastname" : "Frost"
}

Resolves #2803.
Original pull request: #896.
2021-02-16 14:44:51 +01:00
Mark Paluch
c1417c4e4b Polishing.
Move registerSerializersIn(…) entirely to GeoJsonSerializersModule. Tweak Javadoc and wording.

Original pull request: #3539.
Closes #3517
2021-02-02 14:50:48 +01:00
Christoph Strobl
36515abad4 Reduce visibility of GeoJsonSerializersModule.
This commit reduces the visibility of the GeoJsonSerializersModule and instead offers static methods on GeoJsonModule allowing to obtain those via a static method.
The actual serialization was simpified by moving some of its code to a common base class.
Updated reference documentation - relates to: spring-projects/spring-data-commons#2288

We also did, by intent, not change the current GeoJsonModule to add the serializers by default in order to give users time to prepare for that change which will be done with the next major release.

Original pull request: #3539.
Closes #3517
2021-02-02 14:37:57 +01:00
Bjorn Harvold
cba9088b5e Added a serializers module to all GeoJson types with unit tests.
Original pull request: #3539.
Closes #3517
2021-02-02 14:37:57 +01:00
Christoph Strobl
a33aece85d Allow access to mongoDatabaseFactory used in ReactiveMongoTemplate.
By offering a getter method for the ReactiveMongoDatabaseFactory users subclassing ReactiveMongoTemplate could evaluate the current transaction state via ReactiveMongoDatabaseUtils.isTransactionActive(getDatabaseFactory()).
This change also aligns the reactive and imperative template implementation in that regard.

Closes #3540
Original pull request: #3541.
2021-02-02 14:21:37 +01:00
Christoph Strobl
076d334b3c Update count vs. estimatedCount documentation.
Closes #3055
Original pull request: #3541.
2021-02-02 14:21:25 +01:00
Christoph Strobl
e644692a8a Fix Criteria chaining for Criteria.alike().
This commit fixes an issue where an Example probe would not be added to the criteria chain.

Closes #3544
Original pull request: #3549.
2021-02-01 09:00:17 +01:00
Mark Paluch
1d547ec150 Refine Kotlin extensions for MongoOperations.aggregate and aggregateStream
We now provide extensions accepting the input- and output type as reified generic types.

See #3508.
2021-01-27 10:03:44 +01:00
Mark Paluch
ce3066dc59 Polishing.
Align type variable naming with imperative extensions(I, O). Add extension without accepting KClass. Update since tags and tests.

See #3508.
Original pull request: #893.
2021-01-27 09:57:29 +01:00
wonwoo
c11dcd19ee Add missing ReactiveMongoOperations.aggregate Kotlin extension.
See #3508.
Original pull request: #893.
2021-01-27 09:57:10 +01:00
Mark Paluch
1d60cd7e98 Polishing.
Tweak wording in the docs. Remove unused code. Fix generics. Rename AggregateContext to AggregationOperation to AggregationDefinition to avoid yet another Context object.

See #3542.
Original pull request: #3545.
2021-01-27 09:36:47 +01:00
Christoph Strobl
4700b4dda2 Use relaxed type mapping for aggregations by default.
This commit switches from a strict to a relaxed type mapping for aggregation executions. This allows users to add fields to the aggregation that might be part of the stored document but not necessarily of its java model representation.
Instead of throwing an exception in those cases the relaxed type check will go on with the user provided field names.
To restore the original behaviour use the strictMapping() option on AggregationOptions.

Closes #3542
Original pull request: #3545.
2021-01-27 09:36:41 +01:00
Christoph Strobl
91f1dc1c6a Update QBE Documentation section.
This commit adds a note explaining scenarios suitable for an UntypedExampleMatcher.

Closes: #3474
Original pull request: #3538.
2021-01-26 14:59:15 +01:00
Mark Paluch
70d87a9f71 Filter spring-issuemaster comments from feedback provided reassignment.
See #3529
2021-01-20 14:50:19 +01:00
Christoph Strobl
427b468891 Fix method names in full text query documentation.
Closes #3525
2021-01-20 08:29:44 +01:00
Mark Paluch
30ed3350c7 Filter spring-issuemaster comments from feedback provided reassignment.
See #3529
2021-01-14 11:05:52 +01:00
Christoph Strobl
78e04f0b42 After release cleanups.
See #3521
2021-01-13 15:47:00 +01:00
Christoph Strobl
f311bdfbb4 Prepare next development iteration.
See #3521
2021-01-13 15:46:58 +01:00
Christoph Strobl
a96e75bb64 Release version 3.2 M2 (2021.0.0).
See #3521
2021-01-13 15:34:04 +01:00
Christoph Strobl
dacb88e97f Prepare 3.2 M2 (2021.0.0).
See #3521
2021-01-13 15:33:34 +01:00
Christoph Strobl
59f276f2b5 Updated changelog.
See #3521
2021-01-13 15:33:23 +01:00
Christoph Strobl
8ecb09b142 Updated changelog.
See #3477
2021-01-13 15:16:18 +01:00
Christoph Strobl
c1c25b88e7 Update issue tracker references after GitHub issues migration.
See: #3529
2021-01-12 13:42:57 +01:00
Christoph Strobl
b5effeb4d8 Deprecate KPropertyPath in favor of Spring Data Common's KPropertyPath.
relates to: spring-projects/spring-data-commons#478

Original Pull Request: #3533
Closes: #3515
2021-01-12 13:42:35 +01:00
Mark Paluch
ad6d2c97b7 Update copyright year to 2021.
Closes #3534
2021-01-12 11:50:17 +01:00
Mark Paluch
8b0ecf17c4 DATAMONGO-2651 - Polishing.
Update since tag. Reduce test class/method visibility, update license headers.

Original pull request: #898.
2021-01-11 14:49:12 +01:00
Christoph Strobl
19e62787b8 DATAMONGO-2651 - Support $accumulator in GroupOperationBuilder.
Original pull request: #898.
2021-01-11 14:49:06 +01:00
Mark Paluch
b8298ed23d DATAMONGO-2671 - Polishing.
Fix copyright header.

Original pull request: #897.
2021-01-11 12:14:24 +01:00
Mark Paluch
3277673e39 DATAMONGO-2671 - Polishing.
Fix copyright header. Add since tags.

Original pull request: #897.
2021-01-11 12:14:24 +01:00
Christoph Strobl
b56e17e0eb DATAMONGO-2671 - Fix dateFromParts millisecond field name.
Use millisecond instead of milliseconds field name.

Related to: https://jira.mongodb.org/browse/DOCS-10652
Original pull request: #897.
2021-01-11 12:14:20 +01:00
Mark Paluch
4d10962d12 #3529 - Add GitHub actions workflow for issue management. 2020-12-31 10:37:23 +01:00
Greg L. Turnquist
b7310fd1ae DATAMONGO-2665 - Use Docker hub credentials for all CI jobs, 2020-12-14 16:43:15 -06:00
Mark Paluch
c66ffeaa09 DATAMONGO-2653 - Updated changelog. 2020-12-09 16:47:38 +01:00
Mark Paluch
d1c6b0cd19 DATAMONGO-2649 - After release cleanups. 2020-12-09 15:32:19 +01:00
Mark Paluch
b5d5485196 DATAMONGO-2649 - Prepare next development iteration. 2020-12-09 15:32:15 +01:00
Mark Paluch
3982536301 DATAMONGO-2649 - Release version 3.2 M1 (2021.0.0). 2020-12-09 15:21:55 +01:00
Mark Paluch
1e84f379b2 DATAMONGO-2649 - Prepare 3.2 M1 (2021.0.0). 2020-12-09 15:21:28 +01:00
Mark Paluch
d605a227fc DATAMONGO-2649 - Updated changelog. 2020-12-09 15:21:25 +01:00
Mark Paluch
8dea071270 DATAMONGO-2647 - Updated changelog. 2020-12-09 12:42:22 +01:00
Mark Paluch
fece1e99cb DATAMONGO-2646 - Updated changelog. 2020-12-09 09:59:08 +01:00
Mark Paluch
8918c97189 DATAMONGO-2663 - Document Spring Data to MongoDB compatibility.
Original Pull Request: #895
2020-12-07 14:39:20 +01:00
Mark Paluch
3f5cc897da DATAMONGO-2659 - Polishing.
Update Javadoc to reflect find and aggregation nature. Use primitive boolean on Query.allowDiskUse to avoid nullable type usage. Update ReactiveMongoTemplate to consider allowDiskUse.

Original pull request: #891.
2020-12-01 09:42:09 +01:00
abarkan
9d5b72db49 DATAMONGO-2659 - Allow disk use on query.
Original pull request: #891.
2020-12-01 09:41:34 +01:00
Mark Paluch
65401bf4c3 DATAMONGO-2661 - Polishing.
Add ticket reference.

Original pull request: #894.
2020-11-26 11:48:32 +01:00
Yoann de Martino
c8b64601db DATAMONGO-2661 - Handle nullable types for KPropertyPath.
Original pull request: #894.
2020-11-26 11:48:32 +01:00
Mark Paluch
ab4fe5cb0b DATAMONGO-2652 - Polishing.
Reorder implementation methods. Reduce visibility of test methods according to JUnit 5 requirements.

Original pull request: #892.
2020-11-25 14:38:11 +01:00
Jens Schauder
c1a8ffec96 DATAMONGO-2652 - Implements CrudRepository and ReactiveCrudRepository.delete(Iterable<ID> ids).
See also: DATACMNS-800.
Original pull request: #892.
2020-11-25 11:34:03 +01:00
Mark Paluch
5c3bb00b24 DATAMONGO-2648 - Updated changelog. 2020-11-11 12:34:36 +01:00
Christoph Strobl
07c728bb32 DATAMONGO-2644 - ProjectOperation no longer errors on inclusion of default _id field.
Original pull request: #890.
2020-11-10 09:39:13 +01:00
Christoph Strobl
c7e1ca5863 DATAMONGO-2635 - Enforce aggregation pipeline mapping.
Avoid using the Aggregation.DEFAULT_CONTEXT which does not map contained values to the according MongoDB representation. We now use a relaxed aggregation context, preserving given field names, where possible.

Original pull request: #890.
2020-11-10 09:39:05 +01:00
Mark Paluch
6ab43c2391 DATAMONGO-2639 - After release cleanups. 2020-10-28 16:10:23 +01:00
Mark Paluch
96f389e580 DATAMONGO-2639 - Prepare next development iteration. 2020-10-28 16:10:20 +01:00
Mark Paluch
c9251b1b29 DATAMONGO-2639 - Release version 3.1 GA (2020.0.0). 2020-10-28 15:46:54 +01:00
Mark Paluch
373f07e176 DATAMONGO-2639 - Prepare 3.1 GA (2020.0.0). 2020-10-28 15:46:31 +01:00
Mark Paluch
f5e2bdc7ef DATAMONGO-2639 - Updated changelog. 2020-10-28 15:46:17 +01:00
Mark Paluch
30e63fffe2 DATAMONGO-2625 - Updated changelog. 2020-10-28 15:03:01 +01:00
Mark Paluch
83136b4e60 DATAMONGO-2624 - Updated changelog. 2020-10-28 12:15:04 +01:00
Mark Paluch
56697545a3 DATAMONGO-2641 - Updated changelog. 2020-10-28 11:32:27 +01:00
Robin Dupret
76eecc443e DATAMONGO-2638 - Fix list item rendering in reference documentation.
Original Pull Request: #885
2020-10-27 13:31:45 +01:00
LiangYong
1f81806809 DATAMONGO-2638 - Fix aggregation input parameter syntax in reference documentation.
Original Pull Request: #881
2020-10-27 13:31:35 +01:00
Greg L. Turnquist
2d348be5b2 DATAMONGO-2629 - Use JDK 15 for next CI jobs. 2020-10-26 13:26:11 -05:00
Christoph Strobl
bbbe369093 DATAMONGO-2642 - Upgrade MongoDB drivers to 4.1.1. 2020-10-26 12:46:07 +01:00
Christoph Strobl
5aa29fc7b8 DATAMONGO-2626 - After release cleanups. 2020-10-14 14:48:47 +02:00
Christoph Strobl
05fc6546ff DATAMONGO-2626 - Prepare next development iteration. 2020-10-14 14:48:45 +02:00
Christoph Strobl
2c6e645a3d DATAMONGO-2626 - Release version 3.1 RC2 (2020.0.0). 2020-10-14 14:28:55 +02:00
Christoph Strobl
20f702512b DATAMONGO-2626 - Prepare 3.1 RC2 (2020.0.0). 2020-10-14 14:27:37 +02:00
Christoph Strobl
ad77f23364 DATAMONGO-2626 - Updated changelog. 2020-10-14 14:27:30 +02:00
Mark Paluch
9af8a73290 DATAMONGO-2616 - Polishing.
Reformat code. Merge if-statements.

Original pull request: #889.
2020-10-07 11:35:47 +02:00
Christoph Strobl
aaa4557887 DATAMONGO-2616 - Short circuit id value assignment in MongoConverter.
Original pull request: #889.
2020-10-07 11:35:40 +02:00
Mark Paluch
217be64a77 DATAMONGO-2623 - Polishing.
Avoid nullable method arguments and add assertions. Introduce build() method to AccumulatorFinalizeBuilder to build Accumulator without specifying a finalize function.

Original pull request: #887.
2020-10-07 09:51:08 +02:00
Christoph Strobl
0ef852a8fc DATAMONGO-2623 - Add support for $function and $accumulator aggregation operators.
Original pull request: #887.
2020-10-07 09:50:51 +02:00
Mark Paluch
26f0a1c7f9 DATAMONGO-2622 - Polishing.
Rename AggregationPipeline.requiresRelaxedChecking() to containsUnionWith() to avoid the concept of field validation leaking into AggregationPipeline.

Refactor AggregationOperation to consistently check their type and fallback to the operator check to allow for consistent checks when using custo AggregationOperations.

Original pull request: #886.
2020-10-06 12:09:18 +02:00
Christoph Strobl
230c32041a DATAMONGO-2622 - Add support for $unionWith aggregation stage.
We now support the $unionWith aggregation stage via the UnionWithOperation that performs a union of two collections by combining pipeline results, potentially containing duplicates, into a single result set that is handed over to the next stage.
In order to remove duplicates it is possible to append a GroupOperation right after UnionWithOperation.
If the UnionWithOperation uses a pipeline to process documents, field names within the pipeline will be treated as is. In order to map domain type property names to actual field names (considering potential org.springframework.data.mongodb.core.mapping.Field annotations) make sure the enclosing aggregation is a TypedAggregation and provide the target type for the $unionWith stage via mapFieldsTo(Class).

Original pull request: #886.
2020-10-06 12:09:12 +02:00
Mark Paluch
4548d07826 DATAMONGO-2596 - Polishing.
Refactor KPropertyPath.toString() into KProperty.asPath() extension function to allow rendering simple properties and property paths into a String property path.

Original pull request: #880.
2020-10-06 10:18:52 +02:00
Yoann de Martino
b879ec8c0f DATAMONGO-2596 - Introduce extension to render KProperty/KPropertyPath as property path.
Original pull request: #880.
2020-10-06 10:18:19 +02:00
Mark Paluch
c0581c4943 DATAMONGO-2294 - Polishing.
Reorganize imports after Delomboking. Use for-loop instead of Stream.forEach(…). Add Javadoc to methods. Add since tags.

Simplify tests.

Original pull request: #761.
2020-10-05 17:00:58 +02:00
owen-q
85022d24f3 DATAMONGO-2294 - Support query projections with collection types.
Query include/exclude now accepts a vararg array of fields to specify multiple fields at once.

Original pull request: #761.
2020-10-05 17:00:37 +02:00
Christoph Strobl
b2927ab419 DATAMONGO-2633 - Fix json parsing of nested arrays in ParameterBindingDocumentCodec.
Original pull request: #888.
2020-10-05 15:34:50 +02:00
Mark Paluch
91c39e2825 DATAMONGO-2630 - Add support for suspend repository query methods returning List<T>. 2020-09-22 15:01:09 +02:00
Greg L. Turnquist
965a34efd3 DATAMONGO-2629 - Only test other versions for local changes on main branch. 2020-09-18 11:08:38 -05:00
Mark Paluch
046cbb52a1 DATAMONGO-2608 - After release cleanups. 2020-09-16 14:05:28 +02:00
Mark Paluch
edfd07a3d0 DATAMONGO-2608 - Prepare next development iteration. 2020-09-16 14:05:24 +02:00
Mark Paluch
b4befc36c0 DATAMONGO-2608 - Release version 3.1 RC1 (2020.0.0). 2020-09-16 13:57:41 +02:00
Mark Paluch
6034fc1cbd DATAMONGO-2608 - Prepare 3.1 RC1 (2020.0.0). 2020-09-16 13:57:08 +02:00
Mark Paluch
61f4770b4a DATAMONGO-2608 - Updated changelog. 2020-09-16 13:56:57 +02:00
Mark Paluch
c9cfe7acd6 DATAMONGO-2609 - Updated changelog. 2020-09-16 12:16:30 +02:00
Mark Paluch
415ceeef63 DATAMONGO-2593 - Updated changelog. 2020-09-16 11:20:07 +02:00
Mark Paluch
1bdcb88430 DATAMONGO-2592 - Updated changelog. 2020-09-16 10:38:57 +02:00
Christoph Strobl
1a134aa444 DATAMONGO-2618 - Fix visibility of ReplaceRootDocumentOperation. 2020-09-14 13:43:56 +02:00
Mark Paluch
c1da95f5dc DATAMONGO-2621 - Adapt to changed array assertions in AssertJ. 2020-09-09 15:55:48 +02:00
Christoph Strobl
c9c005400c DATAMONGO-2613 - Polishing.
Use the opportunity to remove public modifiers from touched test class.

Original Pull Request: #883
2020-08-20 09:00:21 +02:00
Michal Kurcius
b388659c3f DATAMONGO-2613 - Fix single element ArrayJsonSchemaObject to document mapping.
Now toDocument calls toDocument on items correctly.

Original Pull Request: #883
2020-08-20 08:59:46 +02:00
Mark Paluch
90aa7b8f89 DATAMONGO-2594 - Updated changelog. 2020-08-12 13:25:47 +02:00
Mark Paluch
542de64711 DATAMONGO-2579 - After release cleanups. 2020-08-12 12:00:22 +02:00
Mark Paluch
88b1f9fcb3 DATAMONGO-2579 - Prepare next development iteration. 2020-08-12 12:00:19 +02:00
Mark Paluch
450365992a DATAMONGO-2579 - Release version 3.1 M2 (2020.0.0). 2020-08-12 11:52:05 +02:00
Mark Paluch
fd25f39236 DATAMONGO-2579 - Prepare 3.1 M2 (2020.0.0). 2020-08-12 11:51:40 +02:00
Mark Paluch
a7e3ed2e37 DATAMONGO-2579 - Updated changelog. 2020-08-12 11:51:28 +02:00
Mark Paluch
5795a507bd DATAMONGO-1836 - Polishing.
Revert constructor change of AggregationOptions to not break existing code. Update since tags. Reformat code.

Align visibility of AggregationOptionsTests with JUnit 5 rules. Update documentation.

Original pull request: #878.
2020-08-06 11:25:41 +02:00
Yadhukrishna S Pai
22bd3e64be DATAMONGO-1836 - Add support to hint in aggregation options.
Original pull request: #878.
2020-08-06 11:25:36 +02:00
Mark Paluch
6e47d5c76e DATAMONGO-2603 - Polishing.
Add missing Deprecated annotation.
2020-08-04 13:35:26 +02:00
Mark Paluch
bfab233d2f DATAMONGO-2603 - Adopt to Reactor 3.4 changes.
Align with ContextView and changes in other operators.
2020-08-04 13:35:26 +02:00
Christoph Strobl
c6f12ef0e2 DATAMONGO-2602 - Upgrade MongoDB drivers to 4.1.0 2020-08-03 17:14:24 +02:00
Mark Paluch
707ad8e232 DATAMONGO-1894 - Polishing.
Preinitialize EvaluationContextProvider with ReactiveQueryMethodEvaluationContextProvider to not require setting properties on vanilla ReactiveMongoRepositoryFactory objects.
2020-07-31 11:44:07 +02:00
Mark Paluch
b1f5717d63 DATAMONGO-2601 - Suppress results for suspended query methods returning kotlin.Unit.
We now discard results for suspended query methods if the return type is kotlin.Unit.

Related ticket: DATACMNS-1779
2020-07-31 11:44:07 +02:00
Mark Paluch
95c9789f43 DATAMONGO-2599 - Eagerly consider enum types as simple types.
MongoSimpleTypes now eagerly checks if a type is a simple one to avoid PersistentEntity registration for ChronoUnit.
2020-07-30 16:19:10 +02:00
Mark Paluch
8e84d397e2 DATAMONGO-2564 - Fix link to code of conduct. 2020-07-28 15:40:26 +02:00
Mark Paluch
2ea3ceda2d DATAMONGO-2598 - Polishing.
Original pull request: #872.
2020-07-28 15:21:05 +02:00
Jay Bryant
6a43f28466 DATAMONGO-2598 - Wording changes.
Removed the language of oppression and violence
and replaced it with more neutral language.

Note that problematic words in the code have
to remain in the docs until the code changes.

Original pull request: #872.
2020-07-28 15:20:55 +02:00
Mark Paluch
a44a0034b7 DATAMONGO-2557 - Polishing.
Inline methods.

Original pull request: #879.
2020-07-27 09:02:05 +02:00
Christoph Strobl
0085c8063a DATAMONGO-2557 - Use configured CodecRegistry when parsing String based queries instead of default one.
Original pull request: #879.
2020-07-27 09:01:58 +02:00
Christoph Strobl
873fffa202 DATAMONGO-1894 - Polishing.
Remove superfluous Optional wrappers and unify SpEL dependency resolution.

Original Pull Request: #874
2020-07-22 14:02:12 +02:00
Mark Paluch
41607b10d0 DATAMONGO-1894 - Introduce cached ExpressionParser.
Original Pull Request: #874
2020-07-22 14:01:47 +02:00
Mark Paluch
66fae82798 DATAMONGO-1894 - Use reactive SpEL extensions for SpEL evaluation in query execution.
Original Pull Request: #874
2020-07-22 14:01:20 +02:00
Christoph Strobl
00aaf2145b DATAMONGO-2591 - Upgrade MongoDB drivers to 4.1.0-rc0. 2020-07-22 13:27:51 +02:00
Mark Paluch
430c166a2b DATAMONGO-2568 - Updated changelog. 2020-07-22 10:37:57 +02:00
Mark Paluch
79c647a4d8 DATAMONGO-2567 - Updated changelog. 2020-07-22 10:08:43 +02:00
Mark Paluch
1b5a22730b DATAMONGO-2566 - Updated changelog. 2020-07-22 09:44:28 +02:00
Christoph Strobl
a8a364c2de DATAMONGO-2586 - Polishing.
Add tests to ensure no reactive auditing callback is registered when using imperative configuration and vice versa.
Update wording and minor code style tweaks.

Original Pull Request: #877
2020-07-17 11:09:35 +02:00
Mark Paluch
6bafcea539 DATAMONGO-2586 - Add support for reactive auditing.
We now provide a fully reactive variant for auditing with EnableReactiveMongoAuditing.

Original Pull Request: #877
2020-07-17 10:42:41 +02:00
Mark Paluch
2c1a3cf03e DATAMONGO-2536 - Polishing.
Encapsulate skipResults in AggregationOptions. Reformat code. Add override Javadoc.

Original pull request: #876.
2020-07-16 09:42:42 +02:00
Christoph Strobl
6cb89d7452 DATAMONGO-2536 - Add option to skip reading aggregation result.
Introduce dedicated AggregationPipeline to encapsulate pipeline stages.

Original pull request: #876.
2020-07-16 09:42:26 +02:00
Mark Paluch
2026f8729e DATAMONGO-2571 - Polishing.
Reduce test method visibility for JUnit 5.

Original pull request: #873.
2020-07-15 15:33:38 +02:00
Christoph Strobl
bf89400182 DATAMONGO-2571 - Fix regular expression parameter binding for String-based queries.
Original pull request: #873.
2020-07-15 15:33:30 +02:00
Mark Paluch
6c8cb9eb85 DATAMONGO-2490 - Polishing.
Remove unnecessary code. Reuse session-associated collection when logging to avoid unqualified calls to MongoDbFactory.getMongoDatabase(). Create collection before transaction in test for compatibility with older MongoDB servers.

Original pull request: #875.
2020-07-15 15:13:58 +02:00
Christoph Strobl
966504dfa6 DATAMONGO-2490 - Fix dbref fetching during ongoing transaction.
Original pull request: #875.
2020-07-15 15:13:50 +02:00
Mark Paluch
b266bd6feb DATAMONGO-2544 - After release cleanups. 2020-06-25 11:58:22 +02:00
Mark Paluch
a6a4a0b3b6 DATAMONGO-2544 - Prepare next development iteration. 2020-06-25 11:58:19 +02:00
Mark Paluch
2a66cadaa6 DATAMONGO-2544 - Release version 3.1 M1 (2020.0.0). 2020-06-25 11:48:49 +02:00
Mark Paluch
a70629697b DATAMONGO-2544 - Prepare 3.1 M1 (2020.0.0). 2020-06-25 11:48:19 +02:00
Mark Paluch
d52785533d DATAMONGO-2544 - Updated changelog. 2020-06-25 11:48:10 +02:00
Christoph Strobl
cee1d976de DATAMONGO-2285 - Polishing.
Preserve existing logic translating com.mongodb.MongoBulkWriteException that might be thrown by calling MongoOperations.insertAll(Collection), and move bulk operation translation to DefaultBulkOperations.
Along the lines remove the no longer used PersistenceExceptionTranslator from DefaultBulkOperations.

Original Pull Request: #862
2020-06-23 13:22:03 +02:00
Jacob Botuck
f907dbc559 DATAMONGO-2285 - Throw BulkOperationException instead of translated one when running bulk operations.
Return BulkOperationException unless it is a writeConcernError in which case use existing behavior.

Original Pull Request: #862
2020-06-23 13:21:24 +02:00
Christoph Strobl
613d085bb7 DATAMONGO-1569 - Polishing.
Update Javadoc and avoid unrelated index creation during tests due to class path scanning.

Original Pull Request: #738
2020-06-22 13:32:03 +02:00
Christoph Strobl
94a64a156f DATAMONGO-1569 - Add partialFilter to Indexed annotation.
Original Pull Request: #738
2020-06-22 13:32:03 +02:00
Dave Perryman
41e60e5c25 DATAMONGO-1569 - Add support for partial filter expressions in compound index annotations
Original Pull Request: #738
2020-06-22 13:32:03 +02:00
Christoph Strobl
a254576a6e DATAMONGO-2574 - Polishing.
Fix issue in reactive API and add unit tests.

Original Pull Request: #868
2020-06-22 13:32:03 +02:00
konradend
390b5e7b7e DATAMONGO-2574 - Do not overwrite contentType for GridFsFile.
Original Pull Request: #868
2020-06-22 13:32:03 +02:00
Mark Paluch
66dcb8f662 DATAMONGO-2576 - Upgrade to Hibernate Validator 5.4.3.
Add also javax.el to avoid failures in early expression language initialization.
2020-06-22 13:21:32 +02:00
Christoph Strobl
2eaa2d38af DATAMONGO-2556 - Polishing.
Original pull request: #867.
2020-06-22 13:02:14 +02:00
Christoph Strobl
1290898c2b DATAMONGO-2556 - Add estimatedCount for collections.
The newly introduced methods delegate to the drivers MongoCollection.estimatedDocumentCount.

Original pull request: #867.
2020-06-22 13:02:06 +02:00
Mark Paluch
c4ae269b14 DATAMONGO-2570 - Polishing.
Add assertions. Use method references where possible.

Original pull request: #871.
2020-06-22 10:39:44 +02:00
Mehran Behnam
a4ef46d641 DATAMONGO-2570 - Change type of count variable to primitive.
Avoiding unintentional unboxing.

Original pull request: #871.
2020-06-22 10:39:25 +02:00
Mark Paluch
a27939808b DATAMONGO-2558 - Polishing.
Fixed issue number in tests.

Original pull request: #866.
2020-06-21 20:04:09 +02:00
Mark Paluch
da7fc927fa DATAMONGO-2558 - Add integration test for RxJava 3 repositories.
Update Javadoc and reference documentation.

Original pull request: #866.
2020-06-21 20:03:30 +02:00
Christoph Strobl
f768906684 DATAMONGO-2572 - Remove trailing whitespaces from xsd files.
Original Pull Request: #870
2020-06-17 13:07:00 +02:00
Mark Paluch
61a228f8ac DATAMONGO-2572 - Remove usage of Oppressive Language.
Replaced blacklist with denylist and introduce meta keyword SECONDARY_READS as we no longer use MongoDB API with the initial replication concept.

Original Pull Request: #870
2020-06-17 13:05:45 +02:00
Mark Paluch
837b333d7a DATAMONGO-2543 - Updated changelog. 2020-06-10 14:30:55 +02:00
Mark Paluch
ffd4166b65 DATAMONGO-2533 - Updated changelog. 2020-06-10 12:29:55 +02:00
Mark Paluch
083050fc3c DATAMONGO-2532 - Updated changelog. 2020-06-10 11:48:52 +02:00
Mark Paluch
efbf9c8305 DATAMONGO-2565 - Polishing.
Add unit test to verify behavior. Cleanup code.

Original pull request: #869.
2020-06-10 10:25:25 +02:00
BraveLeeLee
4fdf171f7d DATAMONGO-2565 - Evaluate correct expression when obtaining collation from MongoPersistentEntity.
Original pull request: #869.
2020-06-10 10:25:25 +02:00
Mark Paluch
76990f4915 DATAMONGO-2564 - Use standard Spring code of conduct.
Using https://github.com/spring-projects/.github/blob/master/CODE_OF_CONDUCT.md.
2020-06-09 16:10:27 +02:00
Mark Paluch
4defad57c9 DATAMONGO-2562 - Polishing.
Fix typo in exception message.
2020-06-09 11:18:25 +02:00
Mark Paluch
431f7e6b78 DATAMONGO-2562 - Fix return type detection for suspended Kotlin methods.
See DATACMNS-1738 for further reference.
2020-06-09 11:18:25 +02:00
Mark Paluch
e5157f1c17 DATAMONGO-2560 - Upgrade MongoDB drivers to 4.0.4. 2020-06-08 15:54:53 +02:00
Mark Paluch
af091bf6be DATAMONGO-2542 - Polishing.
Fix nullable annotation.

Original pull request: #863.
2020-05-26 10:32:03 +02:00
Christoph Strobl
84ac0e8a85 DATAMONGO-2542 - Shortcut PersistentPropertyPath resolution during query mapping.
By shortcutting the path resolution we avoid checking keywords like $in against a potential path expression.

Original pull request: #863.
2020-05-26 10:31:57 +02:00
Mark Paluch
2a150adc40 DATAMONGO-2545 - Polishing.
Fix warnings and typos.

Original pull request: #864.
2020-05-26 10:14:18 +02:00
Christoph Strobl
feb3018d19 DATAMONGO-2545 - Fix full Query Document binding resulting from SpEL.
We reenabled annotated queries using a SpEL expression resulting in the actual query document.

Original pull request: #864.
2020-05-26 10:14:14 +02:00
Christoph Strobl
3af7269dbb DATAMONGO-2545 - Fix regression in String query SpEL parameter binding.
We reenabled parameter binding within SpEL using query parameter placeholders ?0, ?1,... instead of their array index [0],[1],...

Original pull request: #864.
2020-05-26 10:14:08 +02:00
Christoph Strobl
af39b422b6 DATAMONGO-2547 - Use target class ClassLoader instead of default CL when creating proxy instances.
Original pull request: #865.
2020-05-26 08:50:01 +02:00
Mark Paluch
8b50778350 DATAMONGO-2553 - Fix reference documentation links.
Remove links to removed documentations sections.
2020-05-19 11:36:37 +02:00
Mark Paluch
ce2f8a7bf5 DATAMONGO-2538 - Polishing.
Reformat code. Convert utility classes to abstract ones.

Original pull request: #861.
2020-05-14 11:02:38 +02:00
Christoph Strobl
26fa0c8285 DATAMONGO-2538 - Delombok source files.
Original pull request: #861.
2020-05-14 11:02:20 +02:00
Mark Paluch
3fda554f81 DATAMONGO-2534 - After release cleanups. 2020-05-12 12:40:30 +02:00
Mark Paluch
c6a86226e0 DATAMONGO-2534 - Prepare next development iteration. 2020-05-12 12:40:28 +02:00
Mark Paluch
f88d1de068 DATAMONGO-2534 - Release version 3.0 GA (Neumann). 2020-05-12 12:28:23 +02:00
Mark Paluch
62bfde2b6b DATAMONGO-2534 - Prepare 3.0 GA (Neumann). 2020-05-12 12:27:59 +02:00
Mark Paluch
93a27f80a3 DATAMONGO-2534 - Updated changelog. 2020-05-12 12:27:47 +02:00
Christoph Strobl
c2b0090ff1 DATAMONGO-2541 - Upgrade to MongoDB 4.0.3 Drivers. 2020-05-11 17:00:39 +02:00
Florian Bernard
0345abb5f8 DATAMONGO-2509 - Add missing Query constructor in reference documentation.
Original pull request: #846.
2020-05-06 11:52:16 +02:00
Mark Paluch
35196e3129 DATAMONGO-2509 - Polishing.
Fix typos, improve wording. Reworks documentation specific to MongoDB 3 and 4.

Original pull request: #853.
2020-05-06 11:46:29 +02:00
Christoph Strobl
37d99c4948 DATAMONGO-2509 - Update Javadoc.
Original pull request: #853.
2020-05-06 11:21:11 +02:00
Christoph Strobl
288e04b2d3 DATAMONGO-2509 - Update Reference Documentation.
Related to: DATAMONGO-365, DATAMONGO-384, DATAMONGO-2192, DATAMONGO-2407

Original pull request: #853.
2020-05-06 11:21:02 +02:00
Greg Turnquist
689c1480bd DATAMONGO-2535 - Remove Travis CI. 2020-05-04 15:09:00 -05:00
Mark Paluch
09fbe6060e DATAMONGO-2503 - After release cleanups. 2020-04-28 15:11:43 +02:00
Mark Paluch
d5cf3dfc22 DATAMONGO-2503 - Prepare next development iteration. 2020-04-28 15:11:42 +02:00
Mark Paluch
0f987f44ef DATAMONGO-2503 - Release version 3.0 RC2 (Neumann). 2020-04-28 15:03:53 +02:00
Mark Paluch
5df22233d8 DATAMONGO-2503 - Prepare 3.0 RC2 (Neumann). 2020-04-28 15:03:33 +02:00
Mark Paluch
9751c6bc8b DATAMONGO-2503 - Updated changelog. 2020-04-28 15:03:26 +02:00
Mark Paluch
7dc509953a DATAMONGO-2500 - Updated changelog. 2020-04-28 14:46:50 +02:00
Mark Paluch
2f4f1e524d DATAMONGO-2484 - Updated changelog. 2020-04-28 11:59:01 +02:00
Christoph Strobl
26ddf9d59f DATAMONGO-2531 - Fix MongoClientSettings UUID configuration hook in MongoConfigurationSupport.
Client code overriding configureClientSettings does not automatically remove the default UUidRepresentation settings.
2020-04-27 09:30:37 +02:00
Mark Paluch
96ff4e1d14 DATAMONGO-2461 - Polishing.
Remove superfluous Test annotation as RepeatFailedTest acts as a TestTemplate so adding the Test annotation causes the test to run twice.
2020-04-24 09:03:18 +02:00
Mark Paluch
2af13c27a7 DATAMONGO-2529 - Ensure that MappingMongoConverter.read(…) is never called with null.
Previously, various methods attempted to pass a null argument as source for the converter. The API is non-null and implementations relying on these constraints were easily breakable.

We now make sure that the source is never null.
2020-04-23 14:57:52 +02:00
Mark Paluch
f4d2fc6231 DATAMONGO-2504 - Polishing.
Update equals/hashCode implementation to use the Spring Data form. Make fields final where possible. Use diamond syntax. Reorder methods. Reformat code. Extend tests.

Original pull request: #848.
2020-04-23 12:24:26 +02:00
ddebray
3ab679bcc7 DATAMONGO-2504 - Add hashCode and equals to TextCriteria and Term.
Original pull request: #848.
2020-04-23 12:24:10 +02:00
Mark Paluch
318d552797 DATAMONGO-2505 - Polishing.
Simplify operators. Remove Lombok usage from newly introduced code. Update reference documentation. Reformat code.

Original pull request: #854.
2020-04-23 12:02:46 +02:00
Mathieu Ouellet
8cfbd39c7e DATAMONGO-2505 - Deferred Database retrieval from ReactiveMongoDatabaseFactory.
Change ReactiveMongoDatabaseFactory#getMongoDatabase() methods return Mono to enable access to the subscriber context.

Original pull request: #854.
2020-04-23 12:02:15 +02:00
Christoph Strobl
3a14af5485 DATAMONGO-2513 - Fix Eq aggregation operator comparing collection values.
Original pull request: #855.
2020-04-22 11:46:49 +02:00
Mark Paluch
00034d899a DATAMONGO-2516 - Polishing.
Reflect nullability change in TextScore Javadoc. Update documentation.

Original pull request: #856.
2020-04-22 11:12:50 +02:00
Christoph Strobl
fba6d7d8be DATAMONGO-2516 - Assert compatibility with MongoDB 4.4-rc0.
Fixes:
- Fields list must not contain text search score property when no $text criteria present.
- Sort must not be an empty document when running map reduce.
- Timeout in tests creating indexes.

Changes:
- score property might now be null when not having a $text criteria present. Was zero before.

Original pull request: #856.
2020-04-22 11:12:29 +02:00
Mark Paluch
95c4707902 DATAMONGO-2523 - Polishing.
Reformat code.

Original pull request: #859.
2020-04-22 10:14:50 +02:00
Christoph Strobl
32f3e60c9f DATAMONGO-2523 - Fix Json binding of SpEL expressions in arrays.
The closing bracket must not have a leading whitespace.

Original pull request: #859.
2020-04-22 10:08:57 +02:00
Mark Paluch
b57e571033 DATAMONGO-2517 - Polishing.
Reformat code.

Original pull request: #857.
2020-04-21 16:02:09 +02:00
Christoph Strobl
6604c507dd DATAMONGO-2517 - Fix invalid entity creation for text queries.
Fix a glitch in the MappingMongoConverter that uses the single String argument constructor (since it matches in type and parameter count to the given input string) to falsely instantiate an Entity when it should not.

Original pull request: #857.
2020-04-21 16:02:04 +02:00
Christoph Strobl
e1df28797a DATAMONGO-2507 - Polishing.
Add 'matching' default method also to imperative variant (ExecutableFindOperation), fix & add tests using 'distinct'.
Update Javadoc and rename input arg 'criteriaDefinition' to 'criteria'.

Original Pull Request: #852
2020-04-14 10:22:01 +02:00
Juergen Zimmermann
c6630aa279 DATAMONGO-2507 - Add default method matching(CriteriaDefinition) to ReactiveFindOperation.DistinctWithQuery.
Original Pull Request: #852
2020-04-14 09:51:23 +02:00
Greg Turnquist
bf921cdbd7 DATAMONGO-2510 - Use JDK 14 for Java.NEXT CI testing. 2020-04-09 14:29:16 -05:00
Christoph Strobl
a1b4e6df59 DATAMONGO-2508 - Upgrade to MongoDB 4.0.2 Drivers. 2020-04-08 11:38:19 +02:00
Christoph Strobl
4b3312998a DATAMONGO-2506 - Provide meaningful error message when using unsupported return type in repository aggregation method.
We improved the error message for unsupported return types instead of running into an IllegalArgumentException for unique results.

Original pull request: #851.
2020-04-07 14:58:38 +02:00
Mark Paluch
c5501db577 DATAMONGO-2502 - Polishing.
Extend tests. Fix generics. Consistently use compiled patterns for positional placeholder removal.

Original pull request: #847.
2020-04-07 14:10:20 +02:00
Christoph Strobl
936a0d35f7 DATAMONGO-2502 - Fix nested array path mapping for updates.
Original pull request: #847.
2020-04-07 14:10:09 +02:00
Christoph Strobl
5dd91d0b6d DATAMONGO-1677 - Polishing.
Switch tests to JUnit Jupiter.

Original Pull Request: #849
2020-04-06 08:51:30 +02:00
Jens Schauder
28510de6c8 DATAMONGO-1677 - Adds a test to confirm a query with more than 10 arguments works just fine.
Original Pull Request: #849
2020-04-06 08:50:56 +02:00
Mark Paluch
4bbf4cd5cf DATAMONGO-2492 - After release cleanups. 2020-03-31 15:08:05 +02:00
Mark Paluch
90bd3f0f18 DATAMONGO-2492 - Prepare next development iteration. 2020-03-31 15:08:04 +02:00
Mark Paluch
1e35116419 DATAMONGO-2492 - Release version 3.0 RC1 (Neumann). 2020-03-31 14:59:41 +02:00
Mark Paluch
dd336f0ecb DATAMONGO-2492 - Prepare 3.0 RC1 (Neumann). 2020-03-31 14:59:20 +02:00
Mark Paluch
d020219ded DATAMONGO-2492 - Updated changelog. 2020-03-31 14:59:15 +02:00
Mark Paluch
0345eff69a DATAMONGO-2477 - Polishing.
Make sure that indexes get created where needed.
2020-03-30 14:37:42 +02:00
Mark Paluch
55fee27fb6 DATAMONGO-625 - Polishing.
Introduce default interface methods where possible. Rename save(…) to store(…) to align with method naming. Reduce constructor visibility to avoid invalid API usage. Replace mutable object in builder with fields to avoid mutation of already built objects when reusing the builder.
Remove Options.chunked(…) factory method to avoid confusion with chunkSize method.

Reformat code, strip trailing whitespaces.

Original pull request: #842.
2020-03-30 14:19:45 +02:00
Christoph Strobl
ffba352e15 DATAMONGO-625 - Add support for GridFS with predefined id.
We now support storing GridFS content with predefined id, which allows to replace an existing resource instead of having to delete and reupload it.

Original pull request: #842.
2020-03-30 14:19:26 +02:00
Mark Paluch
1118df5550 DATAMONGO-2477 - Polishing.
Remove warn log for auto-index creation. Remove unused fields. Document index creation in reference documentation.

Original pull request: #845.
2020-03-26 15:14:03 +01:00
Christoph Strobl
29f05af733 DATAMONGO-2477 - Disable auto index creation by default.
Original pull request: #845.
2020-03-26 15:14:03 +01:00
Oliver Drotbohm
7bac739146 DATAMONGO-2501 - Upgrade to Querydsl 4.3.
Adapted to changes in the APT APIs.
2020-03-26 14:38:51 +01:00
Mark Paluch
6366d3cec1 DATAMONGO-2485 - Updated changelog. 2020-03-25 10:59:47 +01:00
Christoph Strobl
44913abd80 DATAMONGO-2300 - Polishing.
Move null check to event publishing logic.

Original Pull Request: #763
2020-03-23 09:29:49 +01:00
Heesu Jung
7a7f7c942d DATAMONGO-2300 - Add check rawType is null in readMap.
Original Pull Request: #763
2020-03-23 09:29:19 +01:00
Christoph Strobl
e9c9938016 DATAMONGO-2498 - Upgrade to MongoDB 4.0.1 Drivers. 2020-03-23 09:18:07 +01:00
Mark Paluch
c9da0a75ff DATAMONGO-931 - Polishing.
Reformat code. Add private constructor to prevent unwanted instantiation.

Original pull request: #844.
2020-03-20 14:45:11 +01:00
Christoph Strobl
581961e79a DATAMONGO-931 - Add support for $redact aggregation.
We now support $redact via Aggregation.redact.

Aggregation.redact(ConditionalOperators.when(Criteria.where("level").is(5))
    .then(RedactOperation.PRUNE)
    .otherwise(RedactOperation.DESCEND));

Original pull request: #844.
2020-03-20 14:40:16 +01:00
Christoph Strobl
0e0d726457 DATAMONGO-2475 - Polishing.
Fix reduction of $and/$or operations with more than two arguments.

Original Pull Request: #834
2020-03-20 10:15:10 +01:00
Enrique León Molina
7b5fea960f DATAMONGO-2475 - MongodbDocumentSerializer: reduce nested ANDs and ORs.
Reduce the number of nested $and / $or clauses by combining them into a single document where possible. This allows to simplify the following statement

{
  "$or": [
    {
      "$or": [
        {
          "$or": [
            {
              "$or": [
                { "firstname": "Hencxjo" },
                { "lastname": "Leon" }
              ]
            },
            { "age": { "$lte": 30 } }
          ]
        },
        { "age": { "$gte": 20 } }
      ]
    },
    { "uniqueId": { "$exists": false } }
  ]
}

to just

{
 "$or": [
   { "firstname": "Hencxjo" },
   { "lastname": "Leon" },
   { "age": { "$lte": 30 } },
   { "age": { "$gte": 20 } },
   { "uniqueId": { "$exists": false } }
 ]
}

Original Pull Request: #834
2020-03-20 10:13:37 +01:00
Mark Paluch
a04821ff90 DATAMONGO-2497 - Update documentation regarding @Transient properties usage in the persistence constructor. 2020-03-19 15:37:30 +01:00
Mark Paluch
a6bd41bcf2 DATAMONGO-2416 - Polishing.
Reduce visibility of JUnit 5 test classes/methods.

Original Pull Request: #840
2020-03-17 11:41:39 +01:00
Mark Paluch
6387eb9762 DATAMONGO-2416 - Add convenience methods accepting CriteriaDefinition on Fluent API.
The fluent API now exposes default interface methods accepting CriteriaDefinition for a more concise expression of queries that do not require a Query object.

template.query(Person.class).matching(where("firstname").is("luke")).all()

instead of

template.query(Person.class).matching(query(where("firstname").is("luke"))).all()

Original Pull Request: #840
2020-03-17 11:41:14 +01:00
Mark Paluch
5fb4b036bb DATAMONGO-1026 - Include documentation about custom conversions.
We now include the documentations partial about custom conversions that explains default converter registrations, overrides and system setting timezone-sensitivity.
2020-03-17 10:57:15 +01:00
Mark Paluch
4f0dc04a81 DATAMONGO-2479 - Polishing.
Tweak Javadoc. Update reference documentation. Slightly refactor reactive flows to reduce operator count.

Simplify test fixtures and remove Google Guava usage. Reformat code.

Original pull request: #839.
2020-03-16 11:34:27 +01:00
Roman Puchkovskiy
ee59c6b774 DATAMONGO-2479 - Add AfterConvertCallback and AfterSaveCallback (and their reactive versions).
Previously, only BeforeConvertCallback and BeforeSaveCallback were supported (and their reactive counterparts). This commit adds support for 'after-convert' and 'after-save' events using entity callbacks feature.

Original pull request: #839.
2020-03-16 11:34:13 +01:00
Mark Paluch
b0b905ddb7 DATAMONGO-2488 - Polishing.
Simplify conditional entity check. Reduce test method visibility for JUnit 5.

Original pull request: #841.
2020-03-11 14:51:03 +01:00
Christoph Strobl
7f7be5e47d DATAMONGO-2488 - Fix nested array path field name mapping.
Original pull request: #841.
2020-03-11 14:37:36 +01:00
Jens Schauder
5a49aa6519 DATAMONGO-2473 - After release cleanups. 2020-03-11 09:57:42 +01:00
Jens Schauder
b68079c421 DATAMONGO-2473 - Prepare next development iteration. 2020-03-11 09:57:41 +01:00
Jens Schauder
fde49f2a5a DATAMONGO-2473 - Release version 3.0 M4 (Neumann). 2020-03-11 09:47:07 +01:00
Jens Schauder
4d73d76b9f DATAMONGO-2473 - Prepare 3.0 M4 (Neumann). 2020-03-11 09:46:29 +01:00
Jens Schauder
8f2c806403 DATAMONGO-2473 - Updated changelog. 2020-03-11 09:46:17 +01:00
Mark Paluch
d0eb76946e DATAMONGO-2491 - Adapt to Mockito 3.3 changes.
Mockito reports falsely unnecessary stubbings so we're switching to the silent runner for these cases.
2020-03-11 09:14:53 +01:00
Mark Paluch
df43d7fcdb DATAMONGO-2355 - Refactor Abstract…Configuration classes to avoid need for cglib proxies.
Configuration methods now use parameter injections to avoid the need for cglib subclassing.
2020-03-10 14:17:37 +01:00
Mark Paluch
7b34a602ed DATAMONGO-2355 - Declare concrete Template API class type on AbstractReactiveMongoConfiguration.
We now declare bean methods returning Template API types with their concrete implementation to allow for improved introspection of bean definitions.
2020-03-10 13:55:41 +01:00
Mark Paluch
c829387c82 DATAMONGO-2363 - Polishing.
Introduce support for SpEL aggregation expressions for AddFields and Set operations.

Rearrange methods. Make fields final where possible.

Original pull request: #801.
2020-03-09 14:09:00 +01:00
Christoph Strobl
a4e12a96c9 DATAMONGO-2363 - Add support for $merge and $addFields aggregation stage.
MergeOperation.builder().intoCollection("monthlytotals")
    .whenDocumentsMatchApply(
        newAggregation(
            AddFieldsOperation.builder()
                .addField("thumbsup").withValueOf(sumOf("thumbsup").and("$$new.thumbsup"))
                .addField("thumbsdown").withValueOf(sumOf("thumbsdown").and("$$new.thumbsdown"))
                .build()
        )
    )
    .whenDocumentsDontMatch(insertNewDocument())
    .build()

Original pull request: #801.
2020-03-09 14:08:53 +01:00
Mark Paluch
7e3f7bd861 DATAMONGO-2481 - Polishing.
Add since tag.

Original pull request: #838.
2020-03-06 12:20:29 +01:00
Mark Paluch
46ab6b4c94 DATAMONGO-2481 - Polishing.
Migrate more tests to JUnit 5. Rearrange methods. Reduce method visibility according to JUnit 5 requirements.

Remove Java 11 build and only use Java 8 and 13.

Original pull request: #838.
2020-03-06 12:20:26 +01:00
Christoph Strobl
8029acb3fb DATAMONGO-2481 - Improve build time.
Introduce Junit Jupiter extensions.
Flush collections instead of dropping them.
Apply cursor timeout to change stream and capped collections in tests.

Original pull request: #838.
2020-03-06 12:20:20 +01:00
Christoph Strobl
96ffb0b7f4 DATAMONGO-2489 - Upgrade to MongoDB 4.0 Drivers. 2020-03-06 09:20:55 +01:00
Mark Paluch
7849b5333b DATAMONGO-2453 - Updated changelog. 2020-02-26 11:55:05 +01:00
Mark Paluch
fb45b4eb2a DATAMONGO-2452 - Updated changelog. 2020-02-26 11:31:48 +01:00
Mark Paluch
a6a84421b4 DATAMONGO-2478 - Polishing.
Convert test to JUnit 5.

Original pull request: #836.
2020-02-24 11:34:26 +01:00
Christoph Strobl
c4dcc7d0f5 DATAMONGO-2478 - Fix NPE in Query.of when given a proxied source.
Original pull request: #836.
2020-02-24 11:32:09 +01:00
Mark Paluch
c25a1a9e53 DATAMONGO-2476 - Polishing.
Convert test to JUnit 5.

Original pull request: #835.
2020-02-24 11:29:10 +01:00
Christoph Strobl
81c68955fe DATAMONGO-2476 - Fix Json parsing for unquoted placeholders in arrays.
Original pull request: #835.
2020-02-24 11:07:16 +01:00
Mark Paluch
22ca597fca DATAMONGO-2341 - Polishing.
Inline MongoPersistentEntity.idPropertyIsShardKey() into UpdateContext. Move mapped shard key cache to QueryOperations level. Simplify conditionals. Tweak documentation.

Original pull request: #833.
2020-02-17 10:17:35 +01:00
Christoph Strobl
6259cd2c3b DATAMONGO-2341 - Support shard key derivation in save operations via @Sharded annotation.
Spring Data MongoDB uses the @Sharded annotation to identify entities stored in sharded collections.
The shard key consists of a single or multiple properties present in every document within the target collection, and is used to distribute them across shards.

Spring Data MongoDB will do best effort optimisations for sharded scenarios when using repositories by adding required shard key information, if not already present, to replaceOne filter queries when upserting entities. This may require an additional server round trip to determine the actual value of the current shard key.

By setting @Sharded(immutableKey = true) no attempt will be made to check if an entities shard key changed.

Please see the MongoDB Documentation for further details and the list below for which operations are eligible to auto include the shard key.

* Reactive/CrudRepository.save(...)
* Reactive/CrudRepository.saveAll(...)
* Reactive/MongoTemplate.save(...)

Original pull request: #833.
2020-02-17 10:17:20 +01:00
Christoph Strobl
f153399c3b DATAMONGO-2474 - Upgrade to MongoDB driver 4.0.0-rc0. 2020-02-14 07:44:03 +01:00
Mark Paluch
65508eb01b DATAMONGO-2456 - After release cleanups. 2020-02-12 15:04:22 +01:00
Mark Paluch
a7c25c8524 DATAMONGO-2456 - Prepare next development iteration. 2020-02-12 15:04:21 +01:00
Mark Paluch
087f8f78b5 DATAMONGO-2456 - Release version 3.0 M3 (Neumann). 2020-02-12 14:47:16 +01:00
Mark Paluch
534ce2e5f5 DATAMONGO-2456 - Prepare 3.0 M3 (Neumann). 2020-02-12 14:46:56 +01:00
Mark Paluch
0f4f745d3c DATAMONGO-2456 - Updated changelog. 2020-02-12 14:46:51 +01:00
Mark Paluch
ca802c7ca4 DATAMONGO-2470 - Adapt tests to AssertJ 3.15.0. 2020-02-11 10:57:52 +01:00
Mark Paluch
e9d14f41a5 DATAMONGO-2400 - Polishing.
Adapt to changes in commons. Add functional create method to MongoCustomConversions. Update Javadoc and reference documentation. Truncate precision for Java 11 build compatibility in tests.

Original pull request: #810.
2020-02-07 14:16:53 +01:00
Christoph Strobl
3b6880edfd DATAMONGO-2400 - Consider java.time.Instant a store supported native type and add configuration options for other java.time types.
We now use the MongoDB Java driver InstantCodec instead of a dedicated converter. Other java.time types like LocalDate use a different zone offset when writing values which can lead to unexpected behavior. Therefore we added configuration options to MongoCustomConversions that allow to tell the conversion sub system which approach to use when writing those kind of types.

Original pull request: #810.
2020-02-07 12:32:58 +01:00
Mark Paluch
0b77906a83 DATAMONGO-2461 - Polishing.
Extend Javadoc. Reformat code. Reduce log level to info. Refactor resource disposal to use Store.CloseableResource.

Original pull request: #831.
2020-02-05 10:35:58 +01:00
Christoph Strobl
993018feb1 DATAMONGO-2461 - Efficient resource usage and ci related improvments.
- Give the server a little time to think on ci system.
- Reuse and Close MongoClients in tests.
- Use WriteConcern majority in setup.
- Use longer transaction timeout on server
- Use junit-pioneer to repeatable tests known to fail due to network errors.

Original pull request: #831.
2020-02-05 10:35:51 +01:00
Mark Paluch
dd15bbc5c1 DATAMONGO-2079 - Reduce visibility of MappingMongoConverter.getValueInternal.
Do not expose a method that is used internally.

Original Pull Request: #832
2020-02-04 14:21:46 +01:00
Mark Paluch
f6c62d6e2f DATAMONGO-2079 - MappingMongoConverter no longer implements ValueResolver.
MappingMongoConverter no longer implements a package-private interface so that converter instances can be proxied.

Original Pull Request: #832
2020-02-04 14:21:19 +01:00
Christoph Strobl
632c499cf1 DATAMONGO-2417 - Update Copyright headers of Kotlin extensions and test.
Original Pull Request: #809
2020-02-04 08:55:12 +01:00
Mark Paluch
2c9956723e DATAMONGO-2417 - Typesafe Kotlin Extension for distinct queries.
We now provide extensions for imperative and reactive distinct queries accepting Kotlin's KProperty and KProperty1 to express type-safe queries:

mongo.query<Customer>().distinct(Customer::name)

mongo.distinct(Customer::name)

Original Pull Request: #809
2020-02-04 08:54:37 +01:00
Mark Paluch
d0c2c820d7 DATAMONGO-2464 - Polishing.
Apply fix also to reactive MongoDB repository documentation.

Original pull request: #816.
2020-02-03 11:34:00 +01:00
LiangYong
f69ddb6c61 DATAMONGO-2464 - Fix code examples in reference documentation.
fixed repository miss "{" issue.

Original pull request: #816.
2020-02-03 11:34:00 +01:00
Mark Paluch
073668b1d1 DATAMONGO-2460 - Polishing.
Reformat code. Use diamond syntax.

Original pull request: #830.
2020-02-03 11:25:25 +01:00
Christoph Strobl
291d84591c DATAMONGO-2460 - Fix target type computation for complex id properties with @Field annotation.
We now set the target type to org.bson.Document for id properties annotated with @Field having the implicit target type derived from the annotation. Along the lines we fixed warn message when an id property with explicit (unsupported) field name is detected.

Original pull request: #830.
2020-02-03 11:25:11 +01:00
Mark Paluch
46806a5606 DATAMONGO-2449 - Polishing.
Reformat code. Tweak Javadoc.

Original pull request: #827.
2020-02-03 11:02:50 +01:00
Christoph Strobl
85519eb84d DATAMONGO-2449 - Evaluate allowDiskUse added to Meta annotation when executing derived Aggregation.
@Meta(allowDiskUse...) allows to set the according aggregation option when executing a String based annotation via a repository definition.

Original pull request: #827.
2020-02-03 11:02:32 +01:00
Mark Paluch
f8ee9648da DATAMONGO-2365 - Polishing.
Reformat code. Fix method name and generics. Whitespaces.

Original pull request: #828.
2020-01-29 13:40:42 +01:00
Christoph Strobl
c7f9274480 DATAMONGO-2365 - Extract common functionality to centralized component.
Share common code paths between reactive and imperative implementation.

Original pull request: #828.
2020-01-29 13:40:39 +01:00
Christoph Strobl
0bc0fff24e DATAMONGO-2365 - Pass on index name to query hint.
Original pull request: #828.
2020-01-29 13:40:28 +01:00
Mark Paluch
c21b35973d DATAMONGO-2462 - Move off deprecated EntityInstantiators.
We now use the newly introduced EntityInstantiator at o.s.d.mapping.model and moved off the deprecated one in o.s.d.convert.
2020-01-29 10:36:45 +01:00
Mark Paluch
44017485fc DATAMONGO-1997 - Polishing.
Tweak documentation. Reformat code. Remove commented code.

Original pull request: #826.
2020-01-29 10:26:25 +01:00
Christoph Strobl
c56a13ad00 DATAMONGO-1997 - Add support to return the single deleted item for a deleteBy query method.
Added support for:

@Nullable
Person deleteSingleByLastname(String lastname);

Optional<Person> deleteByBirthdate(Date birthdate);

Mono<Person> deleteSinglePersonByLastname(String lastname);

Original pull request: #826.
2020-01-29 10:26:19 +01:00
Mark Paluch
0a2ea88f3c DATAMONGO-2406 - Polishing.
Add optimization for Mono.

Original pull request: #825.
2020-01-29 09:57:42 +01:00
Christoph Strobl
80da9e21ed DATAMONGO-2406 - Derived reactive deleteBy query execution should allow Mono<Void> result.
Mono<Void> is now a supported return type of derived reactive deleteBy queries like:

    Mono<Void> deleteByLastname(String lastname);

Original pull request: #825.
2020-01-29 09:57:34 +01:00
Mark Paluch
708466b323 DATAMONGO-2459 - Polishing.
Slightly tweak wording.

Original pull request: #829
2020-01-29 09:52:38 +01:00
Christoph Strobl
2905315452 DATAMONGO-2459 - Add sample for passing on limit and offset using reactive repositories.
Original pull request: #829.
2020-01-29 09:46:20 +01:00
Christoph Strobl
ecc9f3fd60 DATAMONGO-2457 - Fix id type explanation in repository documentation.
Original pull request: #829.
2020-01-29 09:46:15 +01:00
Mark Paluch
c83929c2a3 DATAMONGO-2427 - Simplify docker setup.
Original pull request: #823.
2020-01-27 11:44:02 +01:00
Mark Paluch
9abf098bdb DATAMONGO-2427 - Polishing.
Guard tests.

Original pull request: #823.
2020-01-27 11:43:52 +01:00
Mark Paluch
f688cca400 DATAMONGO-2427 - Switch to MongoDB Driver 4.0.0-beta1.
Enable disabled tests. Adapt to ReactiveGridFS changes.

Use WriteConcern.MAJORITY in tests.

Original pull request: #823.
2020-01-27 11:43:52 +01:00
Christoph Strobl
f09c622b2f DATAMONGO-2427 - Update GridFS API to use MongoDB native ByteBuffer Publisher API and introduce UUID format configuration options.
Move from AsyncInputStream handling to Publisher for GridFS.
UUID types require additional configuration setup to prevent errors while processing legacy (type 3) binary types. We still use type 3 as default but allow codec configuration for type 4 via Java and XML configuration.
Updated migration guide.

Original pull request: #823.
2020-01-27 11:43:52 +01:00
Mark Paluch
6049541d0a DATAMONGO-2427 - Polishing.
Replace leftovers to Mongo 2.x API with Document and MongoDatabase references and tweak Javadoc. Reorder field declarations to class header. Reflect 3.0 versions in schema configuration. Add TODO markers to disabled tests.
Reflect changes in documentation.

Enable disabled test.

Original pull request: #823.
2020-01-27 11:43:52 +01:00
Mark Paluch
2a3f862703 DATAMONGO-2427 - Rename MongoDbFactory to MongoDatabaseFactory.
Rename to follow MongoDB's naming scheme. Re-introduce deprecated MongoDbFactory to aid migration.

Original pull request: #823.
2020-01-27 11:43:51 +01:00
Christoph Strobl
8b97e932a2 DATAMONGO-2427 - Upgrade to MongoDB 4.0 Driver.
This change switches to the MongoDB 4.0 driver and introduces configuration options for com.mongodb.client.MongoClient.
The XML namespace changed from client-options to client-settings and removed already deprecated elements and attributes.

Imports are switched from single artifact uber jar to split imports for driver-core, -sync and -reactivestreams.
Deprecations have been removed.

Original pull request: #823.
2020-01-27 11:43:51 +01:00
Mark Paluch
5f29bee6c9 DATAMONGO-2419 - Enable JDK 11+ builds. 2020-01-22 21:19:55 -06:00
Mark Paluch
5b8037a0ad DATAMONGO-2454 - After release cleanups. 2020-01-17 09:47:50 +01:00
Mark Paluch
1a19e140ee DATAMONGO-2454 - Prepare next development iteration. 2020-01-17 09:47:49 +01:00
Mark Paluch
83307c424f DATAMONGO-2454 - Release version 3.0 M2 (Neumann). 2020-01-17 09:39:03 +01:00
Mark Paluch
8394523645 DATAMONGO-2454 - Prepare 3.0 M2 (Neumann). 2020-01-17 09:38:43 +01:00
Mark Paluch
62be436569 DATAMONGO-2454 - Updated changelog. 2020-01-17 09:38:37 +01:00
Mark Paluch
44e6f5fa3f DATAMONGO-2383 - After release cleanups. 2020-01-16 16:11:55 +01:00
Mark Paluch
f2fb05662f DATAMONGO-2383 - Prepare next development iteration. 2020-01-16 16:11:54 +01:00
Mark Paluch
a1fbe31551 DATAMONGO-2383 - Release version 3.0 M1 (Neumann). 2020-01-16 16:05:23 +01:00
Mark Paluch
fca1a79f81 DATAMONGO-2383 - Prepare 3.0 M1 (Neumann). 2020-01-16 16:05:03 +01:00
Mark Paluch
cbf87e6e49 DATAMONGO-2383 - Updated changelog. 2020-01-16 16:04:59 +01:00
Mark Paluch
af133c26d0 DATAMONGO-2432 - Updated changelog. 2020-01-15 12:51:13 +01:00
Christoph Strobl
ab5b1f0140 DATAMONGO-2451 - Fix value conversion for id properties used in sort expression.
Previously we falsely converted the sort value (1/-1) into the id types target value when a Field annotation had been present.

Original pull request: #822.
2020-01-15 11:51:42 +01:00
Mark Paluch
3a5876537b DATAMONGO-2431 - Updated changelog. 2020-01-15 10:36:36 +01:00
Mark Paluch
48f51d0fb0 DATAMONGO-2450 - Polishing.
Replace stream with for-loop.

Original pull request: #820.
2020-01-15 10:15:14 +01:00
Christoph Strobl
fb499f8c69 DATAMONGO-2450 - Apply array filters to bulk write.
Original pull request: #820.
2020-01-15 10:15:06 +01:00
Mark Paluch
bcc2c94e03 DATAMONGO-2440 - Polishing.
Replace SpringJUnit4ClassRunner with SpringRunner.

Original pull request: #821.
2020-01-15 09:30:12 +01:00
Mark Paluch
284f547e99 DATAMONGO-2437 - Polishing.
Mention changes in Aggregation _id handling in what's new. Reformat code.

Original pull request: #821.
2020-01-15 09:30:09 +01:00
Christoph Strobl
d824f3b8b2 DATAMONGO-2437 - Fix complex id handling when reading aggregation results.
Removed Unwrapping complex id values.
Template.aggregate now behaves like aggregateStream or its reactive counterpart.

Original pull request: #821.
2020-01-15 09:30:07 +01:00
Christoph Strobl
7b1a96f4a9 DATAMONGO-2448 - Bump version to 3.0 SNAPSHOT.
In preparation for the upcoming breaking changes when switching to the MongoDB Java Driver 4.0 and the breaking changes required for that update (expected for Milestone 2), we eagerly bump the version number to 3.0.

Original pull request: #819.
2020-01-13 14:29:09 +01:00
Christoph Strobl
4f75fec5c5 DATAMONGO-2447 - Upgrade MongoDB Drivers to 3.12.0 (sync) and 1.13.0 (reactive). 2020-01-10 11:22:49 +01:00
Mark Paluch
61bd56dd74 DATAMONGO-2442 - Polishing.
Reduce visibility of test methods for JUnit 5 tests.

Original pull request: #818.
2020-01-08 15:12:47 +01:00
Christoph Strobl
b4222c5646 DATAMONGO-2442 - Polishing.
Transition touched test classes to JUnit Jupiter.

Original pull request: #818.
2020-01-08 15:12:44 +01:00
Christoph Strobl
4a45928aee DATAMONGO-2442 - Fix thenValueOf in $cond builder.
We now create a field reference when calling the builder instead of using the value as is.

Original pull request: #818.
2020-01-08 15:12:23 +01:00
Mark Paluch
e2200eccf7 DATAMONGO-2440 - Polishing.
Iterate over List instead of using the Stream API.

Reduce visibility of JUnit 5 test methods. Consolidate assertions.

Original pull request: #817.
2020-01-08 15:01:57 +01:00
Christoph Strobl
96c4901e7f DATAMONGO-2440 - Fix field target type conversion for collection values.
We now preserve the collection nature of the source type when applying custom target type conversions. Prior to this change collection values had been changed to single element causing query errors in MongoDB when using $in queries.

Original pull request: #817.
2020-01-08 15:01:44 +01:00
Christoph Strobl
1393f23f3b DATAMONGO-2423 - Polishing.
Update nullability annotations and reduce visibility in tests.

Original pull request: #815.
2020-01-08 13:24:10 +01:00
Christoph Strobl
9bbe1f2a26 DATAMONGO-2423 - Nullability refinements for Update.
Ease non null restrictions for operators that may use null values like $set.

Original pull request: #815.
2020-01-08 13:23:53 +01:00
Mark Paluch
eacfe2b8f7 DATAMONGO-2444 - Update copyright years to 2020. 2020-01-07 08:59:27 +01:00
Jens Schauder
674f0cca2b DATAMONGO-2422 - Updated changelog. 2019-12-04 14:32:45 +01:00
Jens Schauder
da7b51a51e DATAMONGO-2421 - Updated changelog. 2019-12-04 12:09:46 +01:00
Mark Paluch
a1b5175299 DATAMONGO-2430 - Upgrade to mongo-java-driver 3.11.2. 2019-12-04 11:43:07 +01:00
Mark Paluch
56fff286aa DATAMONGO-2418 - Polishing.
Reformat code.

Original pull request: #814.
2019-12-04 10:32:04 +01:00
Christoph Strobl
60112b4d14 DATAMONGO-2418 - Obtain EvaluationContextExtensions lazily when parsing Bson queries.
An eager evaluation of the context extension can lead to errors when e.g. the security context was not present.

Original pull request: #814.
2019-12-04 10:32:04 +01:00
Mark Paluch
277b7a1c7c DATAMONGO-2410 - Polishing.
Simplify cast. Extend test with DBObject interface.

Original pull request: #813.
2019-12-04 08:56:43 +01:00
Christoph Strobl
c5b892f03b DATAMONGO-2410 - Fix Document to BasicDBObject conversion.
Original pull request: #813.
2019-12-04 08:56:35 +01:00
Mark Paluch
dbf43941be DATAMONGO-765 - Polishing.
Reformat code. Update ticket references.

Original pull request: #806.
2019-11-26 15:21:29 +01:00
Denis Zavedeev
1d98b77f3d DATAMONGO-765 - Support skip and limit parameters in GridFsTemplate and ReactiveGridFsTemplate.
Leverage `skip` and `limit` methods exposed in `GridFSFindIterable` to support limiting and skipping results.
In particular these changes allow the `find(Query)` method to correctly consider parameters of a page request.

Original pull request: #806.
2019-11-26 15:21:04 +01:00
Mark Paluch
cd4e4065ff DATAMONGO-2370 - Polishing.
Align since version to 2.3 until we have an indication for a major version bump. Tweak docs.

Original pull request: #803.
2019-11-20 10:12:34 +01:00
Christoph Strobl
9f4872de4f DATAMONGO-2370 - Polishing.
Use JUnit Jupiter api for tests of touched classes and fix parsing errors in disabled ones.

Original pull request: #803.
2019-11-20 10:12:30 +01:00
Christoph Strobl
7abf69e575 DATAMONGO-2370 - Add support for $round aggregation operator.
Original pull request: #803.
2019-11-20 10:12:27 +01:00
Mark Paluch
588ed2b0e2 DATAMONGO-2402 - Updated changelog. 2019-11-18 12:43:26 +01:00
Mark Paluch
8a228f22cd DATAMONGO-2401 - Updated changelog. 2019-11-18 12:16:26 +01:00
Christoph Strobl
d652b2bdb4 DATAMONGO-2414 - Introduce MongoServerCondition to replace JUnit 4 TestRules.
MongoServerCondition replaces the JUnit 4 TestRules (MongoVersionRule & ReplicaSet) with a JUnit Jupiter ExecutionCondition.

Original Pull Request: #807
2019-11-14 11:10:20 +01:00
Mark Paluch
f7e527e45c DATAMONGO-2414 - Polishing.
Use longer timeout to cater for slower CI environments.

Original Pull Request: #807
2019-11-14 11:09:58 +01:00
Mark Paluch
aede7c9cad DATAMONGO-2414 - Guard drain loop in AsyncInputStreamHandler with state switch.
We now use a non-blocking state switch to determine whether to invoke drainLoop(…) from Subscriber completion.

Previously, we relied on same thread identification assuming if the subscription thread and the completion thread were the same, that we're already running inside the drain loop.
It turns out that a I/O thread could also run in event-loop mode where subscription and completion happens on the same thread but in between there's some processing and so the the call to completion is a delayed signal and not being called on the same stack as drainLoop(…).
The same-thread assumption was in place to avoid StackOverflow caused by infinite recursions.

We now use a state lock to enter the drain loop. Any concurrent attempts to re-enter the drain loop in Subscriber completion is now prevented to make sure that we continue draining while not causing stack recursions.

Original Pull Request: #807
2019-11-14 11:09:19 +01:00
Mark Paluch
1a5de2e1db DATAMONGO-2331 - Polishing.
Remove deprecated methods accepting Update in favor of methods accepting UpdateDefinition in Template APIs.
Hide AggregationUpdate constructor.

Tweak Javadoc and reference documentation.

Original pull request: #789.
2019-11-13 09:51:46 +01:00
Christoph Strobl
cc07a1bbb4 DATAMONGO-2331 - Guard test execution.
Original pull request: #789.
2019-11-13 09:51:39 +01:00
Christoph Strobl
32cbae0e5f DATAMONGO-2331 - Add support for Update with an aggregation pipeline.
Now the update methods exposed by (Reactive)MongoOperations also accept an Aggregation Pipeline via AggregationUpdate.

The update can consist of the following stages:

* AggregationUpdate.set(...).toValue(...) -> $set : { ... }
* AggregationUpdate.unset(...) -> $unset : [ ... ]
* AggregationUpdate.replaceWith(...) -> $replaceWith : { ... }

AggregationUpdate update = Aggregation.newUpdate()
    .set("average").toValue(ArithmeticOperators.valueOf("tests").avg())
    .set("grade").toValue(ConditionalOperators.switchCases(
        when(valueOf("average").greaterThanEqualToValue(90)).then("A"),
        when(valueOf("average").greaterThanEqualToValue(80)).then("B"),
        when(valueOf("average").greaterThanEqualToValue(70)).then("C"),
        when(valueOf("average").greaterThanEqualToValue(60)).then("D"))
        .defaultTo("F")
    );

template.update(Student.class)
    .apply(update)
    .all();

Original pull request: #789.
2019-11-13 09:51:22 +01:00
Mark Paluch
9eaf67148d DATAMONGO-2385 - Polishing.
Remove null checks for arguments known to be not-null. Remove Nullable annotations from methods that never return null.

Original pull request: #802.
2019-11-11 14:17:01 +01:00
Christoph Strobl
ff60149166 DATAMONGO-2385 - Remove unnecessary null checks in MongoConverters.
Original pull request: #802.
2019-11-11 14:10:00 +01:00
Mark Paluch
f7a010827d DATAMONGO-2409 - Polishing.
Adapt also ExecutableFindOperation.DistinctWithProjection.asType() to return the appropriate TerminatingDistinct.

Original pull request: #805.
2019-11-11 10:22:27 +01:00
Christoph Strobl
1e8c4cec5b DATAMONGO-2409 - Fix return type of Kotlin extension function for ReactiveFindOperation.DistinctWithProjection.asType().
Original pull request: #805.
2019-11-11 10:22:22 +01:00
Mark Paluch
0e0b45597b DATAMONGO-2403 - Polishing.
Use handle(…) to skip values instead of flatMap(…) to reduce overhead.

Original pull request: #804.
2019-11-08 13:51:41 +01:00
Christoph Strobl
b014fe4c7c DATAMONGO-2403 - Fix aggregation simple type result retrieval from empty document.
Projections used within an aggregation pipeline can result in empty documents emitted by the driver. We now guarded those cases and skip those documents within a Flux or simply return an empty Mono depending on the methods signature.

Original pull request: #804.
2019-11-08 13:47:56 +01:00
Christoph Strobl
ead7679f21 DATAMONGO-2382 - Updated changelog. 2019-11-04 15:39:54 +01:00
Christoph Strobl
18cf94dc34 DATAMONGO-2381 - Updated changelog. 2019-11-04 10:34:50 +01:00
Christoph Strobl
30d99445e2 DATAMONGO-2393 - Remove capturing lambdas and extract methods.
Original Pull Request: #799
2019-10-31 12:50:33 +01:00
Mark Paluch
839aecee84 DATAMONGO-2393 - Support configurable chunk size.
We now allow consuming GridFS files using a configurable chunk size. The default chunk size is now 256kb.

Original Pull Request: #799
2019-10-31 12:50:09 +01:00
Mark Paluch
c6592b01b0 DATAMONGO-2393 - Polishing.
Extract read requests into inner class.

Original Pull Request: #799
2019-10-31 12:49:45 +01:00
Mark Paluch
48176a833c DATAMONGO-2393 - Fix BufferOverflow in GridFS upload.
AsyncInputStreamAdapter now properly splits and buffers incoming DataBuffers according the read requests of AsyncInputStream.read(…) calls.
Previously, the adapter used the input buffer size to be used as the output buffer size. A larger DataBuffer than the transfer buffer handed in through read(…) caused a BufferOverflow.

Original Pull Request: #799
2019-10-31 12:49:18 +01:00
Mark Paluch
0facdcfa98 DATAMONGO-2393 - Use drain loop for same-thread processing in GridFS download stream.
We now rely on an outer drain-loop when GridFS reads complete on the same thread instead of using recursive subscriptions to avoid StackOverflow. Previously, we recursively invoked subscriptions that lead to an increased stack size.

Original Pull Request: #799
2019-10-31 12:48:55 +01:00
Christoph Strobl
837a9885f2 DATAMONGO-2399 - Upgrade to MongoDB Java Driver 3.11.1 2019-10-30 10:47:47 +01:00
Mark Paluch
6cc5bc627a DATAMONGO-2388 - Polishing.
Use StringJoiner to create comma-delimited String. Add nullability annotations.

Original pull request: #797.
2019-10-28 10:58:17 +01:00
Christoph Strobl
84f7f433f7 DATAMONGO-2388 - Fix CodecConfigurationException when reading index info that contains DbRef.
Provide the default CodecRegistry when converting partial index data to its String representation used in IndexInfo.

Original pull request: #797.
2019-10-28 10:47:22 +01:00
Mark Paluch
7df9e932f7 DATAMONGO-2390 - Polishing.
Reformat code.

Original pull request: #800.
2019-10-28 10:10:26 +01:00
Christoph Strobl
5308e6c37f DATAMONGO-2390 - Polishing.
Switch touched test files to JUnit Jupiter.

Original pull request: #800.
2019-10-28 10:07:16 +01:00
Christoph Strobl
bc1c6c9a64 DATAMONGO-2390 - Add support for maxTimeMS to AggregationOptions.
maxTimeMs defines the time limit for the aggregation operations. If not specified or set to zero, operations will not time out.

Original pull request: #800.
2019-10-28 10:07:08 +01:00
Mark Paluch
62006129ca DATAMONGO-2394 - Polishing.
Reformat code.

Original pull request: #798.
2019-10-28 09:31:53 +01:00
Christoph Strobl
5c2370399f DATAMONGO-2394 - Polishing.
Move tests to JUnit Jupiter.

Original pull request: #798.
2019-10-28 09:31:52 +01:00
Christoph Strobl
3bffe402c0 DATAMONGO-2394 - Fix test issues related to JUnit5 upgrade.
Execution time and test order changed by using JUnit5. This commit fixes some of the issues related to index creation where actually not needed.

Original pull request: #798.
2019-10-28 09:31:50 +01:00
Christoph Strobl
6959c56df6 DATAMONGO-2394 - Fix distance conversion for derived finder using near along with GeoJSON.
GeoJson requries the distance to be in meters instead of radians, so we now make sure to convert it correctly

Original pull request: #798.
2019-10-28 09:31:43 +01:00
Mark Paluch
b5bc4320aa DATAMONGO-2059 - Polishing.
Move query rewriting into CountQuery. Consider existing $and items during query rewrite.

Original pull request: #604.
2019-10-25 09:11:35 +02:00
Christoph Strobl
909c51d00a DATAMONGO-2059 - Replace usage of deprecated collection.count() with collection.countDocuments().
This commit switches from simple collection.count(), operating on potentially false collection statistic,  to countDocuments() using an aggregation for accurate results.
The transition required query modifications at some points because $match does not support $near and $nearSphere but require $geoWithin along with $center or $centerSphere which does not support $minDistance (see https://jira.mongodb.org/browse/SERVER-37043).
$geoWithin further more does not sort results by distance, but this fact can be ignored when just counting matches.

Examples:

{ location : { $near : [-73.99171, 40.738868], $maxDistance : 1.1 } }
{ location : { $geoWithin : { $center: [ [-73.99171, 40.738868], 1.1] } } }

{ location : { $near : [-73.99171, 40.738868], $minDistance : 0.1, $maxDistance : 1.1 } }
{$and :[ { $nor :[ { location :{ $geoWithin :{ $center :[ [-73.99171, 40.738868 ], 0.01] } } } ]}, { location :{ $geoWithin :{ $center :[ [-73.99171, 40.738868 ], 1.1] } } } ] }

Original pull request: #604.
2019-10-25 09:01:12 +02:00
Mark Paluch
4a04e82e86 DATAMONGO-2392 - Polishing.
Add author tags. Move integration tests to existing test class.
Apply more appropriate in existing tests assertions. Use diamond syntax.

Original pull request: #796.
2019-10-16 13:55:00 +02:00
Mark Paluch
1370653c93 DATAMONGO-2392 - Consistently use GridFS file Id instead of ObjectId.
We now consistently use GridFSFile.getId() to allow custom Id usage instead of enforcing the Id to be an ObjectId. Using the native Id allows interaction with files that use a custom Id type.

Original pull request: #796.
2019-10-16 13:54:57 +02:00
Nick Stolwijk
ebfcfb3834 DATAMONGO-2392 - Fix handling in ReactiveGridFsTemplate of GridFS files with custom id type.
Original pull request: #796.
2019-10-16 13:54:29 +02:00
Mark Paluch
77aafc597b DATAMONGO-2334 - After release cleanups. 2019-09-30 16:17:29 +02:00
Mark Paluch
a4503812bd DATAMONGO-2334 - Prepare next development iteration. 2019-09-30 16:17:28 +02:00
Mark Paluch
8943e38944 DATAMONGO-2334 - Release version 2.2 GA (Moore). 2019-09-30 15:51:07 +02:00
Mark Paluch
c700a508d5 DATAMONGO-2334 - Prepare 2.2 GA (Moore). 2019-09-30 15:50:43 +02:00
Mark Paluch
11a23becce DATAMONGO-2334 - Updated changelog. 2019-09-30 15:50:35 +02:00
Mark Paluch
ad2a3483be DATAMONGO-2333 - Updated changelog. 2019-09-30 11:16:16 +02:00
Mark Paluch
499f019798 DATAMONGO-2379 - Polishing.
Reorder what's new to group related items together.

Original Pull Request: #794
2019-09-30 10:21:08 +02:00
Mark Paluch
d0e782687a DATAMONGO-2379 - Add documentation for Kotlin support.
Original Pull Request: #794
2019-09-30 10:01:34 +02:00
Sebastien Deleuze
928134c6e1 DATAMONGO-2380 - Remove @ExperimentalCoroutinesApi annotations.
Original pull request: #795.
2019-09-30 09:43:05 +02:00
Mark Paluch
48034a348d DATAMONGO-2378 - Polishing.
Consistently use MongoTestUtils for client creations. Reuse MongoClient instead of opening always new client instances.

Original pull request: #793.
2019-09-27 10:24:31 +02:00
Christoph Strobl
565132c619 DATAMONGO-2378 - Favor com.mongodb.client.MongoClient (over already deprecated com.mongodb.MongoClient) where possible.
Original pull request: #793.
2019-09-27 10:12:49 +02:00
Mark Paluch
4a012d5654 DATAMONGO-2377 - Polishing.
Reformat code.

Original pull request: #792.
2019-09-25 13:36:51 +02:00
Christoph Strobl
ccb8ae08a6 DATAMONGO-2377 - Fix handling of $$value and $$this in field exposing aggregation.
Internal field references to $$this and $$value are now no longer mapped against exposed fields which had caused errors before.

Original pull request: #792.
2019-09-25 13:36:00 +02:00
Christoph Strobl
8cc0609190 DATAMONGO-1731 - Improve update & upsert documentation. 2019-09-23 13:42:50 +02:00
Mark Paluch
004e8ba0ea DATAMONGO-2360 - Polishing.
Apply index hints in ReactiveMongoTemplate.count(…).

Original pull request: #788.
2019-09-19 14:55:40 +02:00
Christoph Strobl
9093f8d8af DATAMONGO-2360 - Apply query hint to count queries.
Original pull request: #788.
2019-09-19 14:41:13 +02:00
Mark Paluch
801a3645a9 DATAMONGO-2374 - Polishing.
Reformat code.

Original pull request: #791.
2019-09-19 14:15:54 +02:00
Christoph Strobl
9ebe1439f1 DATAMONGO-2374 - Fix simple type result handling for repository query methods.
Original pull request: #791.
2019-09-19 14:07:00 +02:00
Christoph Strobl
26dc0c5c27 DATAMONGO-2366 - Polishing.
Fix typo in reference documentation and add note on error handling.

Original Pull Request: #790
2019-09-19 11:47:03 +02:00
Mark Paluch
6e1d426a87 DATAMONGO-2366 - Consistently handle exceptions in CursorReadingTask.
Exceptions during CursorReadingTask startup and during polling are handled now by the same exception handling to handle Exceptions only once and notify ErrorHandler exactly once per exception.

Previously, startup exceptions relied on exception handling in the execute closure and notified ErrorHandler potentially multiple times.

Original Pull Request: #790
2019-09-19 10:43:57 +02:00
Franz van Betteraey
f549fd18b5 DATAMONGO-2361 - Fix @Document reference documentation.
Original pull request: #787.
2019-09-13 10:50:28 +02:00
Mark Paluch
a3a547a706 DATAMONGO-2335 - After release cleanups. 2019-09-06 10:21:56 +02:00
Mark Paluch
0ff8171309 DATAMONGO-2335 - Prepare next development iteration. 2019-09-06 10:21:54 +02:00
Mark Paluch
63dfb59a3f DATAMONGO-2335 - Release version 2.2 RC3 (Moore). 2019-09-06 10:10:42 +02:00
Mark Paluch
d33ee2ffac DATAMONGO-2335 - Prepare 2.2 RC3 (Moore). 2019-09-06 10:10:12 +02:00
Mark Paluch
59388d99cc DATAMONGO-2335 - Updated changelog. 2019-09-06 10:10:07 +02:00
Christoph Strobl
ee6048e289 DATAMONGO-2357 - Fix read/write for MongoDB client.model GeoJSON types.
We now consider native GeoJSON types of the MongoDB client during conversion passing on the raw values to the driver when writing and using the configured MongoDB codecs on read.

Original pull request: #786.
2019-09-05 15:46:19 +02:00
Christoph Strobl
9a062d53f3 DATAMONGO-2310 - Update documentation for TypedAggregation. 2019-09-05 13:02:01 +02:00
Christoph Strobl
a3c5b07eb7 DATAMONGO-2348 - Update documentation of version property handling. 2019-09-05 10:29:53 +02:00
Christoph Strobl
40d30a230d DATAMONGO-2354 - Polishing.
Same as with FindPublisherPreparer the CursorPreparer needs to be public because it is used in one of the protected methods of MongoTemplate.

Original Pull Request: #784
2019-09-04 13:03:52 +02:00
kostya05983
10116f7c93 DATAMONGO-2354 - Change visibility of FindPublisherPreparer.
The FindPublisherPreparer is used in an protected method of ReactiveMongoTemplate and needs to be public to allow overriding.

Original Pull Request: #784
2019-09-04 13:03:44 +02:00
Mark Paluch
705203c898 DATAMONGO-2358 - Polishing.
Inherit dependency-management for Kotlin Coroutines.

Original pull request: #785.
2019-09-04 11:52:39 +02:00
Sebastien Deleuze
8fb9d9e5f4 DATAMONGO-2358 - Upgrade to Coroutines 1.3.0 and fix warnings.
Original pull request: #785.
2019-09-04 11:40:10 +02:00
Mark Paluch
c23c5ae6c6 DATAMONGO-2356 - Move off deprecated Flux/Mono.usingWhen to their replacement overrides. 2019-09-04 09:37:59 +02:00
Mark Paluch
e67bacf66c DATAMONGO-2352 - Polishing.
Apply typo fixes also to ReactiveMongoOperations.

Original pull request: #782.
2019-09-03 11:28:20 +02:00
Ryan Cloherty
617dbdac3f DATAMONGO-2352 - Fix documentation typos.
Original pull request: #782.
2019-09-03 11:26:47 +02:00
Mark Paluch
8ad4f4b71b DATAMONGO-2344 - Polishing.
Remove generics from FindPublisherPreparer. Rename ReadPreferenceAware.hasReadPreferences to hasReadPreference.

Original pull request: #779.
2019-09-03 11:23:37 +02:00
Christoph Strobl
9048ec83af DATAMONGO-2344 - Fix slaveOK query option not applied correctly.
Since MongoDB 3.6 the slaveOk option translates to the primaryPreferred ReadPreference that is now again applied when executing a find operation.

Original pull request: #779.
2019-09-03 11:23:31 +02:00
Christoph Strobl
b2e3e3fb8e DATAMONGO-2346 - Fix (reactive)auditing of immutable versioned entities.
We now check if the source is still the same object after potentially applying auditing modifications and make sure to pass the audited object on to the mapping layer.

Limited bean inspection scope of event listener tests to avoid side effects in index creation.

Original pull request: #780.
2019-09-03 10:43:29 +02:00
Mark Paluch
e9a2b84af5 DATAMONGO-2349 - Polishing.
Reformat code. Remove duplicate simple types.

Original pull request: #783.
2019-09-03 08:57:55 +02:00
Christoph Strobl
5b8be281fb DATAMONGO-2349 - Fix converter registration for java.time types.
The MongoDB Java Driver does not handle java.time types. Therefore those must not be considered simple types.
The behavior was changed by DATACMNS-1294 forcing usage of Reading & WritingConverter annotations to disambiguate converter direction.
This commit restores the converter registration to the state before the change in Spring Data Commons.

Original pull request: #783.
2019-09-03 08:57:41 +02:00
Christoph Strobl
66b318dabe DATAMONGO-2351 - Polishing.
Fix broken tests and favor StepVerifier over block() for reactive ones.

Original Pull Request: #781
2019-08-23 07:22:09 +02:00
Artyom Gabeev
b78569374a DATAMONGO-2351 - Return zero deleted count for unacknowledged deleteBy.
Original Pull Request: #781
2019-08-23 07:21:55 +02:00
Mark Paluch
79921a7260 DATAMONGO-2342 - Add build job against MongoDB 4.0 2019-08-16 13:19:27 +02:00
Christoph Strobl
bcd8f242e5 DATAMONGO-2342 - Upgrade ci job to MongoDB 4.2
Original pull request: #778.
2019-08-16 11:52:28 +02:00
Christoph Strobl
73fab14b21 DATAMONGO-2342 - Upgrade MongoDB java & reactive streams Driver to 3.11 and 1.12.
Original pull request: #778.
2019-08-16 11:52:23 +02:00
Christoph Strobl
d4505880c7 DATAMONGO-2339 - Fix QueryMapper field name resolution for properties containing underscore.
We now prevent splitting of paths that contain underscores if the entity contains a property that matches.

Original pull request: #777.
2019-08-13 10:26:43 +02:00
Mark Paluch
a54b91392e DATAMONGO-2338 - Open RepositoryFactoryBeans for extension.
createRepositoryFactory() is now no longer final allowing for overriding the method. This change aligns with the remanining store modules.
2019-08-06 15:57:08 +02:00
Mark Paluch
5dc7e7c65f DATAMONGO-2337 - Add HTTPS entries into spring.schemas.
To resolve XSD files properly from the classpath, their HTTPS reference must be present in the spring.schemas to avoid internet interaction for resolving an XSD file.
2019-08-06 15:55:37 +02:00
Greg Turnquist
8802e2c36f DATAMONGO-2280 - Force check for updates. 2019-08-05 11:07:18 -05:00
Mark Paluch
d8189620d2 DATAMONGO-2303 - After release cleanups. 2019-08-05 15:53:02 +02:00
Mark Paluch
fd6411f0ed DATAMONGO-2303 - Prepare next development iteration. 2019-08-05 15:53:01 +02:00
Mark Paluch
445b9c83de DATAMONGO-2303 - Release version 2.2 RC2 (Moore). 2019-08-05 15:35:35 +02:00
Mark Paluch
4e13bda302 DATAMONGO-2303 - Prepare 2.2 RC2 (Moore). 2019-08-05 15:35:05 +02:00
Mark Paluch
e634f2f7c0 DATAMONGO-2303 - Updated changelog. 2019-08-05 15:34:56 +02:00
Mark Paluch
0bb2b8785d DATAMONGO-2302 - Updated changelog. 2019-08-05 11:34:29 +02:00
Mark Paluch
9505112670 DATAMONGO-2272 - Updated changelog. 2019-08-05 11:09:00 +02:00
Mark Paluch
8167f9d199 DATAMONGO-2320 - Polishing.
Use for-loops instead of Stream API and Collectors. Reformat code. Invert condition for smoother readability.

Original pull request: #776.
2019-08-02 10:55:46 +02:00
Christoph Strobl
e6bd8b3ee3 DATAMONGO-2320 - Simplify test code.
Original pull request: #776.
2019-08-02 10:55:46 +02:00
Christoph Strobl
e33c8a3b76 DATAMONGO-2320 - Fix aggregation field reference for $filter operator.
We now render field and local variable references correctly when using the $filter aggregation operator.
Prior to this commit field references had been rendered with an additional $ prefix.

Original pull request: #776.
2019-08-02 10:55:46 +02:00
Mark Paluch
34425c54db DATAMONGO-2327 - Polishing.
Add support for DBRef encoding. Update Javadoc.

Original pull request: #774.
2019-08-01 14:14:43 +02:00
Christoph Strobl
7d9c08409b DATAMONGO-2327 - Add toJson method to Querydsl query support.
This allows to obtain the raw Json representation of the query for eg. debug usage.
We also updated the toString method to return a full Mongo Shell compatible representation of the query including projections, order, skip and limit.

Original pull request: #774.
2019-08-01 14:14:33 +02:00
Mark Paluch
69a4217c4b DATAMONGO-2328 - Polishing.
Replace static imports with qualified access.

Original pull request: #773.
2019-08-01 11:50:20 +02:00
Christoph Strobl
0a0ee417ac DATAMONGO-2328 - Add missing target type conversions for field level type hints.
We now support Date to Long, Date to ObjectId, Script to String and other conversions for both reading and writing scenarios.

Original pull request: #773.
2019-08-01 11:49:54 +02:00
Christoph Strobl
2365dba8d9 DATAMONGO-2330 - Polishing.
Added tests.

Original Pull Request: #775
2019-07-31 14:24:19 +02:00
nkey
4b22558fe7 DATAMONGO-2330 - Apply defaultWriteConcern for bulk operations.
Fixed regression introduced in DATAMONGO-1880.

Original Pull Request: #775
2019-07-31 14:23:48 +02:00
Mark Paluch
75847981c3 DATAMONGO-2312 - Polishing.
Add Javadoc comments.

Original pull request: #770.
2019-07-31 09:52:39 +02:00
Christoph Strobl
0e32b7356c DATAMONGO-2312 - Polishing.
Fix spelling and add missing operator to Sum aggregation operation.

Original pull request: #770.
2019-07-31 09:52:35 +02:00
Christoph Strobl
c2436bcdfc DATAMONGO-2312 - Add support for array projections.
Original pull request: #770.
2019-07-31 09:52:30 +02:00
Mark Paluch
7c25675cbb DATAMONGO-2326 - Upgrade to MongoDB Reactive Streams Driver 1.12.0-rc0. 2019-07-26 10:01:13 +02:00
Mark Paluch
0145b68f61 DATAMONGO-2325 - Upgrade to MongoDB Driver 3.11.0-rc0.
Adapt tests to added overloads.
2019-07-26 09:42:54 +02:00
Mark Paluch
c7ea0782df DATAMONGO-2324 - Adapt to API changes in Commons. 2019-07-26 08:48:33 +02:00
Greg Turnquist
c3ef62a7be DATAMONGO-2280 - Polishing. 2019-07-19 11:46:45 -05:00
Greg Turnquist
0eebf64ec3 DATAMONGO-2280 - Publish documentation for main branch. 2019-07-19 11:46:44 -05:00
Mark Paluch
bdd2b236e8 DATAMONGO-2322 - Polishing.
Suspend change streams tests relying heavily on timing.
2019-07-18 10:06:56 +02:00
Mark Paluch
804106ec9a DATAMONGO-2322 - Handle exceptions thrown by MessageListeners.
ErrorHandlers associated with a CursorReadingTask (Change Streams, imperative Tailable Cursors) now handle exceptions raised by the listener callback.

Exceptions are now catched and the callback continues with the next message.
2019-07-18 09:57:32 +02:00
Mark Paluch
b3e70475eb DATAMONGO-2323 - Polishing.
Use .as(StepVerifier::create) syntax where possible.
2019-07-17 14:35:18 +02:00
Mark Paluch
1f146c3b5c DATAMONGO-2323 - Fix query(…) and stream(…) to be used with BSON Document.
MongoTemplate.stream(…), MongoTemplate.query(…) and ReactiveMongoTemplate.query(…) now no longer fail when used with BSON Document.class.

Previously, field mapping failed because it required an entity type. Now we gracefully back off when find methods are used with a simple Document entity type.
2019-07-17 14:28:11 +02:00
Mark Paluch
d49b1c33b7 DATAMONGO-2306 - Polishing.
Add Nullable annotation to nullable method args. Remove IV from JSON Schema as it is not listed in Mongo specs.

Tweak wording in docs. Parse encryption-settings-ref for MongoClientOptions. Add support for KeyId's in encrypted JSON schema properties.

Original pull request: #766.
2019-07-17 14:03:44 +02:00
Christoph Strobl
da0cb6d766 DATAMONGO-2306 - Add field level encryption to JSON Schema.
We now support encrypted fields via MongoJsonSchema and allow XML configuration of com.mongodb.AutoEncryptionSettings via a dedicated factory bean.

Original pull request: #766.
2019-07-17 14:03:36 +02:00
Mark Paluch
56ac8397aa DATAMONGO-2319 - Deprecate Query.withHint(String) and introduce withHint(Document).
The $hint operator is deprecated since MongoDB 3.2 so we're now deprecating Query.withHint() accepting a String as the String is expected to be a valid document. Therefore, we're introducing withHint(Document) to accept a type-safe representation of query hints.
2019-07-11 15:16:14 +02:00
Mark Paluch
945d3b0085 DATAMONGO-2321 - Polishing.
Reduce AtTest(expected = …) and ExpectedException with the corresponding AssertJ assertThatExceptionOfType(…) and assertThatIllegalArgumentException().isThrownBy(…).
2019-07-11 12:06:27 +02:00
Mark Paluch
fad18341fa DATAMONGO-2321 - Migrate tests to AssertJ. 2019-07-11 11:07:15 +02:00
Mark Paluch
394efa8b82 DATAMONGO-2318 - Fix typo. 2019-07-10 09:46:05 +02:00
Mark Paluch
880b3c6ee0 DATAMONGO-2089 - Polishing.
Loosen assertion to prevent false positives due to non-deterministic ordering.
2019-07-09 15:59:57 +02:00
Mark Paluch
4307c46619 DATAMONGO-2280 - Cleanup release profile.
Reuse inherited configuration from parent pom.
2019-07-09 11:01:38 +02:00
Mark Paluch
86bcfde568 DATAMONGO-2318 - Revise readme for a consistent structure. 2019-07-09 11:01:38 +02:00
Mark Paluch
5b3a9434f1 DATAMONGO-2316 - Configure simple collation on resolved text-indexes for non-simple collation Collections.
We now configure resolved text-indexes with a simple collation when the text index is created in a collection that uses a non-simple collation.

This explicit setting is required by MongoDB to properly create a text index.

Previously, index creation failed.
2019-07-08 13:53:24 +02:00
Mark Paluch
f2ac413c61 DATAMONGO-2188 - Polishing.
Reduce MappingContext requirements in IndexResolver to require only a properly parametrized MappingContext instead of MongoMappingContext.
2019-07-08 13:50:44 +02:00
Christoph Strobl
4e44d07402 DATAMONGO-2307 - Polishing.
Remove unused import and turn static variable into method reference.

Original Pull Request: #765
2019-07-05 12:50:14 +02:00
Michael Simons
1dc6a04d74 DATAMONGO-2307 - Consistently use result of BeforeSaveCallback.
Original Pull Request: #765
2019-07-05 12:50:14 +02:00
Mark Paluch
513e6a0111 DATAMONGO-2315 - Polishing.
Tweak method name. Javadoc.

Original pull request: #772.
2019-07-05 12:15:17 +02:00
Christoph Strobl
8ca16e1cb4 DATAMONGO-2315 - Fix $date parameter binding for string based queries.
Original pull request: #772.
2019-07-05 12:15:10 +02:00
Mark Paluch
296e97903d DATAMONGO-2314 - Polishing.
Reformat code. Remove unnecessary warning suppressions. Switch to diamond syntax.

Original pull request: #771.
2019-07-04 16:26:46 +02:00
Christoph Strobl
617828533e DATAMONGO-2314 - Fix query by example on nested properties.
This fix allows using alike on nested properties.

new Criteria("nested").alike(Example.of(probe, matching().withIgnorePaths("_class"))));

Switch tests to AssertJ.

Original pull request: #771.
2019-07-04 16:26:32 +02:00
Greg Turnquist
c0a22667b9 DATAMONGO-2280 - Use parent 'artifactory' profile for snapshot releases. 2019-07-03 17:10:56 -05:00
Mark Paluch
ada6eb814e DATAMONGO-2089 - Polishing.
Add watchCollection(…) accepting an entity class. Use static import for assertions. Tweak javadoc.

Original pull request: #751.
2019-07-03 11:21:28 +02:00
Christoph Strobl
4a17048ec6 DATAMONGO-2089 - Add fluent change stream API to ReactiveMongoTemplate.
We now offer a fluent API for more intuitive change stream interaction.

Flux<ChangeStreamEvent<User>> flux = reactiveTemplate.changeStream(User.class)
    .watchCollection("people")
    .filter(where("age").gte(38))
    .listen();

Original pull request: #751.
2019-07-03 11:07:03 +02:00
Mark Paluch
06018fa3de DATAMONGO-2287 - Polishing.
Add since tags. Remove final modifier from method args. Switch to lambdas.

Original pull request: #760.
2019-07-02 14:57:37 +02:00
Christoph Strobl
8b406b23ff DATAMONGO-2287 - Polishing.
Add new factory method for ArrayOperators that deals with a collection of values.

Original pull request: #760.
2019-07-02 14:57:37 +02:00
Shashank Sharma
a3ef9b5856 DATAMONGO-2287 - Add support for $in aggregation pipeline operator.
Original pull request: #760.
2019-07-02 14:57:10 +02:00
Mark Paluch
bb280bd59b DATAMONGO-2200 - Polishing.
Tweak Javadoc. Simplify Fields creation from Stream. Remove final modifier from private static method. Iterate with loop over PersistentEntity.

Original pull request: #748.
2019-07-02 14:24:20 +02:00
Christoph Strobl
e24c5e0846 DATAMONGO-2200 - Use mapping context where available.
Use the mapping context to get the required fields or fall back to property descriptors if no mapping context is available.

Original pull request: #748.
2019-07-02 14:24:17 +02:00
Christoph Strobl
839aa1b1e6 DATAMONGO-2200 - Derive fields for aggregation $project stage from a given type.
We now allow to derive field names for a $project stage from a given type by including all top level fields.

    // $project : { title : 1, author : 1 }
    Aggregation.project(Book.class)

Original pull request: #748.
2019-07-02 14:24:09 +02:00
Mark Paluch
ff7a189c98 DATAMONGO-2296 - Polishing.
Use getCollectionName() in MongoTemplate.insert/save. Consistently use getCollectionName(Class) from ReactiveMongoTemplate and fluent API implementations.

Original pull request: #768.
2019-07-01 16:36:46 +02:00
Christoph Strobl
de144a6b0d DATAMONGO-2296 - Consistent use of getCollectionName(Class) throughout MongoTemplate.
Original pull request: #768.
2019-07-01 16:36:38 +02:00
Mark Paluch
bfe514acd7 DATAMONGO-2304 - Polishing.
Align anchor naming. Add code fences to EntityCallbacks.

Original pull request: #767.
2019-07-01 15:10:21 +02:00
Christoph Strobl
87343d2ae5 DATAMONGO-2304 - Fix documentation anchor for entity callback API.
Original pull request: #767.
2019-07-01 15:10:18 +02:00
Christoph Strobl
5e452e1be0 DATAMONGO-2305 - Upgrade to MongoDB Java Driver 3.11.0-beta4.
Tested against 4.0.9 and 4.2.0-rc1 servers.
Added a delay and left a todo in one of the tests where the 4.2.0-rc1 server takes a bit longer than it predecessor when creating indexes which can lead to BackgroundOperationInProgressForNamespace errors.

Original pull request: #764.
2019-07-01 13:31:59 +02:00
Greg Turnquist
8ce8a8307a DATAMONGO-2280 - Only test main branch for upstream triggers. 2019-06-28 19:29:51 -05:00
Greg Turnquist
df94214527 DATAMONGO-2280 - Set user.name and user.home for CI jobs. 2019-06-25 13:33:11 -05:00
Mark Paluch
31f8a63a17 DATAMONGO-2240 - Polishing.
Consistently use this for field access. Access GridFSFile through getter.

Original Pull Request: #741
2019-06-17 14:01:03 +02:00
Mark Paluch
888054bb2a DATAMONGO-2240 - Expose GridFSFile through GridFsResource and ReactiveGridFsResource.
Original Pull Request: #741
2019-06-17 14:00:08 +02:00
Christoph Strobl
29bf74c24c DATAMONGO-2256 - After release cleanups. 2019-06-14 15:12:52 +02:00
Christoph Strobl
1798678e4d DATAMONGO-2256 - Prepare next development iteration. 2019-06-14 15:12:50 +02:00
1170 changed files with 81177 additions and 32942 deletions

View File

@@ -6,7 +6,6 @@ Make sure that:
-->
- [ ] You have read the [Spring Data contribution guidelines](https://github.com/spring-projects/spring-data-build/blob/master/CONTRIBUTING.adoc).
- [ ] There is a ticket in the bug tracker for the project in our [JIRA](https://jira.spring.io/browse/DATAMONGO).
- [ ] You use the code formatters provided [here](https://github.com/spring-projects/spring-data-build/tree/master/etc/ide) and have them applied to your changes. Dont submit any formatting related changes.
- [ ] You submit test cases (unit or integration tests) that back your changes.
- [ ] You added yourself as author in the headers of the classes you touched. Amend the date range in the Apache license header if needed. For new types, add the license header (copy from another file and set the current year only).

47
.github/workflows/project.yml vendored Normal file
View File

@@ -0,0 +1,47 @@
# GitHub Actions to automate GitHub issues for Spring Data Project Management
name: Spring Data GitHub Issues
on:
issues:
types: [opened, edited, reopened]
issue_comment:
types: [created]
pull_request_target:
types: [opened, edited, reopened]
jobs:
Inbox:
runs-on: ubuntu-latest
if: github.repository_owner == 'spring-projects' && (github.event.action == 'opened' || github.event.action == 'reopened') && github.event.pull_request == null
steps:
- name: Create or Update Issue Card
uses: peter-evans/create-or-update-project-card@v1.1.2
with:
project-name: 'Spring Data'
column-name: 'Inbox'
project-location: 'spring-projects'
token: ${{ secrets.GH_ISSUES_TOKEN_SPRING_DATA }}
Pull-Request:
runs-on: ubuntu-latest
if: github.repository_owner == 'spring-projects' && (github.event.action == 'opened' || github.event.action == 'reopened') && github.event.pull_request != null
steps:
- name: Create or Update Pull Request Card
uses: peter-evans/create-or-update-project-card@v1.1.2
with:
project-name: 'Spring Data'
column-name: 'Review pending'
project-location: 'spring-projects'
issue-number: ${{ github.event.pull_request.number }}
token: ${{ secrets.GH_ISSUES_TOKEN_SPRING_DATA }}
Feedback-Provided:
runs-on: ubuntu-latest
if: github.repository_owner == 'spring-projects' && github.event_name == 'issue_comment' && github.event.action == 'created' && github.actor != 'spring-projects-issues' && github.event.pull_request == null && github.event.issue.state == 'open' && contains(toJSON(github.event.issue.labels), 'waiting-for-feedback')
steps:
- name: Update Project Card
uses: peter-evans/create-or-update-project-card@v1.1.2
with:
project-name: 'Spring Data'
column-name: 'Feedback provided'
project-location: 'spring-projects'
token: ${{ secrets.GH_ISSUES_TOKEN_SPRING_DATA }}

View File

@@ -1,110 +0,0 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL =
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: : " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

View File

@@ -1 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip
#Fri Jun 03 09:32:40 CEST 2022
distributionUrl=https\://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.5/apache-maven-3.8.5-bin.zip

View File

@@ -1,38 +0,0 @@
language: java
jdk:
- oraclejdk8
before_install:
- mkdir -p downloads
- mkdir -p var/db var/log
- if [[ ! -d downloads/mongodb-linux-x86_64-ubuntu1604-${MONGO_VERSION} ]] ; then cd downloads && wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-ubuntu1604-${MONGO_VERSION}.tgz && tar xzf mongodb-linux-x86_64-ubuntu1604-${MONGO_VERSION}.tgz && cd ..; fi
- downloads/mongodb-linux-x86_64-ubuntu1604-${MONGO_VERSION}/bin/mongod --version
- downloads/mongodb-linux-x86_64-ubuntu1604-${MONGO_VERSION}/bin/mongod --dbpath var/db --replSet rs0 --fork --logpath var/log/mongod.log
- sleep 10
- |-
downloads/mongodb-linux-x86_64-ubuntu1604-${MONGO_VERSION}/bin/mongo --eval "rs.initiate({_id: 'rs0', members:[{_id: 0, host: '127.0.0.1:27017'}]});"
sleep 15
env:
matrix:
- MONGO_VERSION=4.1.10
- MONGO_VERSION=4.0.4
- MONGO_VERSION=3.6.12
- MONGO_VERSION=3.4.20
global:
- PROFILE=ci
addons:
apt:
packages:
- oracle-java8-installer
sudo: false
cache:
directories:
- $HOME/.m2
- downloads
script: "mvn clean dependency:list test -P${PROFILE} -Dsort"

43
CI.adoc Normal file
View File

@@ -0,0 +1,43 @@
= Continuous Integration
image:https://jenkins.spring.io/buildStatus/icon?job=spring-data-mongodb%2Fmain&subject=Moore%20(main)[link=https://jenkins.spring.io/view/SpringData/job/spring-data-mongodb/]
image:https://jenkins.spring.io/buildStatus/icon?job=spring-data-mongodb%2F2.1.x&subject=Lovelace%20(2.1.x)[link=https://jenkins.spring.io/view/SpringData/job/spring-data-mongodb/]
image:https://jenkins.spring.io/buildStatus/icon?job=spring-data-mongodb%2F1.10.x&subject=Ingalls%20(1.10.x)[link=https://jenkins.spring.io/view/SpringData/job/spring-data-mongodb/]
== Running CI tasks locally
Since this pipeline is purely Docker-based, it's easy to:
* Debug what went wrong on your local machine.
* Test out a a tweak to your test routine before sending it out.
* Experiment against a new image before submitting your pull request.
All of these use cases are great reasons to essentially run what the CI server does on your local machine.
IMPORTANT: To do this you must have Docker installed on your machine.
1. `docker run -it --mount type=bind,source="$(pwd)",target=/spring-data-mongodb-github springci/spring-data-openjdk8-with-mongodb-4.0:latest /bin/bash`
+
This will launch the Docker image and mount your source code at `spring-data-mongodb-github`.
+
2. `cd spring-data-mongodb-github`
+
Next, run the tests from inside the container:
+
3. `./mvnw clean dependency:list test -Dsort -Dbundlor.enabled=false -B` (or with whatever profile you need to test out)
Since the container is binding to your source, you can make edits from your IDE and continue to run build jobs.
If you need to package things up, do this:
1. `docker run -it --mount type=bind,source="$(pwd)",target=/spring-data-mongodb-github springci/spring-data-openjdk8-with-mongodb-4.0:latest /bin/bash`
+
This will launch the Docker image and mount your source code at `spring-data-mongodb-github`.
+
2. `cd spring-data-mongodb-github`
+
Next, package things from inside the container doing this:
+
3. `./mvnw clean dependency:list package -Dsort -Dbundlor.enabled=false -B`
NOTE: Docker containers can eat up disk space fast! From time to time, run `docker system prune` to clean out old images.

View File

@@ -1,27 +0,0 @@
= Contributor Code of Conduct
As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality.
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery
* Personal attacks
* Trolling or insulting/derogatory comments
* Public or private harassment
* Publishing other's private information, such as physical or electronic addresses,
without explicit permission
* Other unethical or unprofessional conduct
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team.
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a project maintainer at spring-code-of-conduct@pivotal.io.
All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances.
Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident.
This Code of Conduct is adapted from the https://contributor-covenant.org[Contributor Covenant], version 1.3.0, available at https://contributor-covenant.org/version/1/3/0/[contributor-covenant.org/version/1/3/0/].

View File

@@ -1,3 +1,3 @@
= Spring Data contribution guidelines
You find the contribution guidelines for Spring Data projects https://github.com/spring-projects/spring-data-build/blob/master/CONTRIBUTING.adoc[here].
You find the contribution guidelines for Spring Data projects https://github.com/spring-projects/spring-data-build/blob/main/CONTRIBUTING.adoc[here].

360
Jenkinsfile vendored
View File

@@ -1,144 +1,218 @@
pipeline {
agent none
triggers {
pollSCM 'H/10 * * * *'
upstream(upstreamProjects: "spring-data-commons/master", threshold: hudson.model.Result.SUCCESS)
}
options {
disableConcurrentBuilds()
}
stages {
stage("Docker images") {
parallel {
stage('Publish JDK 8 + MongoDB 4.0') {
when {
changeset "ci/openjdk8-mongodb-4.0/**"
}
agent any
steps {
script {
def image = docker.build("springci/spring-data-openjdk8-with-mongodb-4.0", "ci/openjdk8-mongodb-4.0/")
docker.withRegistry('', 'hub.docker.com-springbuildmaster') {
image.push()
}
}
}
}
stage('Publish JDK 8 + MongoDB 4.1') {
when {
changeset "ci/openjdk8-mongodb-4.1/**"
}
agent any
steps {
script {
def image = docker.build("springci/spring-data-openjdk8-with-mongodb-4.1", "ci/openjdk8-mongodb-4.1/")
docker.withRegistry('', 'hub.docker.com-springbuildmaster') {
image.push()
}
}
}
}
}
}
stage("test: baseline") {
agent {
docker {
image 'springci/spring-data-openjdk8-with-mongodb-4.0:latest'
args '-v $HOME/.m2:/root/.m2'
}
}
steps {
sh 'mkdir -p /tmp/mongodb/db /tmp/mongodb/log'
sh 'mongod --dbpath /tmp/mongodb/db --replSet rs0 --fork --logpath /tmp/mongodb/log/mongod.log &'
sh 'sleep 10'
sh 'mongo --eval "rs.initiate({_id: \'rs0\', members:[{_id: 0, host: \'127.0.0.1:27017\'}]});"'
sh 'sleep 15'
sh './mvnw clean dependency:list test -Dsort -B'
}
}
stage("Test other configurations") {
parallel {
stage("test: mongodb 4.1") {
agent {
docker {
label 'data'
image 'springci/spring-data-openjdk8-with-mongodb-4.1:latest'
args '-v $HOME/.m2:/root/.m2'
}
}
steps {
sh 'mkdir -p /tmp/mongodb/db /tmp/mongodb/log'
sh 'mongod --dbpath /tmp/mongodb/db --replSet rs0 --fork --logpath /tmp/mongodb/log/mongod.log &'
sh 'sleep 10'
sh 'mongo --eval "rs.initiate({_id: \'rs0\', members:[{_id: 0, host: \'127.0.0.1:27017\'}]});"'
sh 'sleep 15'
sh './mvnw clean dependency:list test -Dsort -B'
}
}
}
}
stage('Release to artifactory') {
when {
branch 'issue/*'
}
agent {
docker {
image 'adoptopenjdk/openjdk8:latest'
args '-v $HOME/.m2:/root/.m2'
}
}
environment {
ARTIFACTORY = credentials('02bd1690-b54f-4c9f-819d-a77cb7a9822c')
}
steps {
sh "./mvnw -Pci,snapshot -Dmaven.test.skip=true clean deploy -B"
}
}
stage('Release to artifactory with docs') {
when {
branch 'master'
}
agent {
docker {
image 'adoptopenjdk/openjdk8:latest'
args '-v $HOME/.m2:/root/.m2'
}
}
environment {
ARTIFACTORY = credentials('02bd1690-b54f-4c9f-819d-a77cb7a9822c')
}
steps {
sh "./mvnw -Pci,snapshot -Dmaven.test.skip=true clean deploy -B"
}
}
}
post {
changed {
script {
slackSend(
color: (currentBuild.currentResult == 'SUCCESS') ? 'good' : 'danger',
channel: '#spring-data-dev',
message: "${currentBuild.fullDisplayName} - `${currentBuild.currentResult}`\n${env.BUILD_URL}")
emailext(
subject: "[${currentBuild.fullDisplayName}] ${currentBuild.currentResult}",
mimeType: 'text/html',
recipientProviders: [[$class: 'CulpritsRecipientProvider'], [$class: 'RequesterRecipientProvider']],
body: "<a href=\"${env.BUILD_URL}\">${currentBuild.fullDisplayName} is reported as ${currentBuild.currentResult}</a>")
}
}
}
def p = [:]
node {
checkout scm
p = readProperties interpolate: true, file: 'ci/pipeline.properties'
}
pipeline {
agent none
triggers {
pollSCM 'H/10 * * * *'
upstream(upstreamProjects: "spring-data-commons/main", threshold: hudson.model.Result.SUCCESS)
}
options {
disableConcurrentBuilds()
buildDiscarder(logRotator(numToKeepStr: '14'))
}
stages {
stage("Docker images") {
parallel {
stage('Publish JDK (Java 17) + MongoDB 4.4') {
when {
anyOf {
changeset "ci/openjdk17-mongodb-4.4/**"
changeset "ci/pipeline.properties"
}
}
agent { label 'data' }
options { timeout(time: 30, unit: 'MINUTES') }
steps {
script {
def image = docker.build("springci/spring-data-with-mongodb-4.4:${p['java.main.tag']}", "--build-arg BASE=${p['docker.java.main.image']} --build-arg MONGODB=${p['docker.mongodb.4.4.version']} ci/openjdk17-mongodb-4.4/")
docker.withRegistry(p['docker.registry'], p['docker.credentials']) {
image.push()
}
}
}
}
stage('Publish JDK (Java 17) + MongoDB 5.0') {
when {
anyOf {
changeset "ci/openjdk17-mongodb-5.0/**"
changeset "ci/pipeline.properties"
}
}
agent { label 'data' }
options { timeout(time: 30, unit: 'MINUTES') }
steps {
script {
def image = docker.build("springci/spring-data-with-mongodb-5.0:${p['java.main.tag']}", "--build-arg BASE=${p['docker.java.main.image']} --build-arg MONGODB=${p['docker.mongodb.5.0.version']} ci/openjdk17-mongodb-5.0/")
docker.withRegistry(p['docker.registry'], p['docker.credentials']) {
image.push()
}
}
}
}
stage('Publish JDK (Java 17) + MongoDB 6.0') {
when {
anyOf {
changeset "ci/openjdk17-mongodb-6.0/**"
changeset "ci/pipeline.properties"
}
}
agent { label 'data' }
options { timeout(time: 30, unit: 'MINUTES') }
steps {
script {
def image = docker.build("springci/spring-data-with-mongodb-6.0:${p['java.main.tag']}", "--build-arg BASE=${p['docker.java.main.image']} --build-arg MONGODB=${p['docker.mongodb.6.0.version']} ci/openjdk17-mongodb-6.0/")
docker.withRegistry(p['docker.registry'], p['docker.credentials']) {
image.push()
}
}
}
}
}
}
stage("test: baseline (Java 17)") {
when {
beforeAgent(true)
anyOf {
branch(pattern: "main|(\\d\\.\\d\\.x)", comparator: "REGEXP")
not { triggeredBy 'UpstreamCause' }
}
}
agent {
label 'data'
}
options { timeout(time: 30, unit: 'MINUTES') }
environment {
ARTIFACTORY = credentials("${p['artifactory.credentials']}")
}
steps {
script {
docker.image("harbor-repo.vmware.com/dockerhub-proxy-cache/springci/spring-data-with-mongodb-4.4:${p['java.main.tag']}").inside(p['docker.java.inside.basic']) {
sh 'mkdir -p /tmp/mongodb/db /tmp/mongodb/log'
sh 'mongod --setParameter transactionLifetimeLimitSeconds=90 --setParameter maxTransactionLockRequestTimeoutMillis=10000 --dbpath /tmp/mongodb/db --replSet rs0 --fork --logpath /tmp/mongodb/log/mongod.log &'
sh 'sleep 10'
sh 'mongo --eval "rs.initiate({_id: \'rs0\', members:[{_id: 0, host: \'127.0.0.1:27017\'}]});"'
sh 'sleep 15'
sh 'MAVEN_OPTS="-Duser.name=jenkins -Duser.home=/tmp/jenkins-home" ./mvnw -s settings.xml clean dependency:list test -Duser.name=jenkins -Dsort -U -B'
}
}
}
}
stage("Test other configurations") {
when {
beforeAgent(true)
allOf {
branch(pattern: "main|(\\d\\.\\d\\.x)", comparator: "REGEXP")
not { triggeredBy 'UpstreamCause' }
}
}
parallel {
stage("test: MongoDB 5.0 (Java 17)") {
agent {
label 'data'
}
options { timeout(time: 30, unit: 'MINUTES') }
environment {
ARTIFACTORY = credentials("${p['artifactory.credentials']}")
}
steps {
script {
docker.image("harbor-repo.vmware.com/dockerhub-proxy-cache/springci/spring-data-with-mongodb-5.0:${p['java.main.tag']}").inside(p['docker.java.inside.basic']) {
sh 'mkdir -p /tmp/mongodb/db /tmp/mongodb/log'
sh 'mongod --setParameter transactionLifetimeLimitSeconds=90 --setParameter maxTransactionLockRequestTimeoutMillis=10000 --dbpath /tmp/mongodb/db --replSet rs0 --fork --logpath /tmp/mongodb/log/mongod.log &'
sh 'sleep 10'
sh 'mongo --eval "rs.initiate({_id: \'rs0\', members:[{_id: 0, host: \'127.0.0.1:27017\'}]});"'
sh 'sleep 15'
sh 'MAVEN_OPTS="-Duser.name=jenkins -Duser.home=/tmp/jenkins-home" ./mvnw -s settings.xml clean dependency:list test -Duser.name=jenkins -Dsort -U -B'
}
}
}
}
stage("test: MongoDB 6.0 (Java 17)") {
agent {
label 'data'
}
options { timeout(time: 30, unit: 'MINUTES') }
environment {
ARTIFACTORY = credentials("${p['artifactory.credentials']}")
}
steps {
script {
docker.image("harbor-repo.vmware.com/dockerhub-proxy-cache/springci/spring-data-with-mongodb-6.0:${p['java.main.tag']}").inside(p['docker.java.inside.basic']) {
sh 'mkdir -p /tmp/mongodb/db /tmp/mongodb/log'
sh 'mongod --setParameter transactionLifetimeLimitSeconds=90 --setParameter maxTransactionLockRequestTimeoutMillis=10000 --dbpath /tmp/mongodb/db --replSet rs0 --fork --logpath /tmp/mongodb/log/mongod.log &'
sh 'sleep 10'
sh 'mongosh --eval "rs.initiate({_id: \'rs0\', members:[{_id: 0, host: \'127.0.0.1:27017\'}]});"'
sh 'sleep 15'
sh 'MAVEN_OPTS="-Duser.name=jenkins -Duser.home=/tmp/jenkins-home" ./mvnw -s settings.xml clean dependency:list test -Duser.name=jenkins -Dsort -U -B'
}
}
}
}
}
}
stage('Release to artifactory') {
when {
beforeAgent(true)
anyOf {
branch(pattern: "main|(\\d\\.\\d\\.x)", comparator: "REGEXP")
not { triggeredBy 'UpstreamCause' }
}
}
agent {
label 'data'
}
options { timeout(time: 20, unit: 'MINUTES') }
environment {
ARTIFACTORY = credentials("${p['artifactory.credentials']}")
}
steps {
script {
docker.image(p['docker.java.main.image']).inside(p['docker.java.inside.basic']) {
sh 'MAVEN_OPTS="-Duser.name=jenkins -Duser.home=/tmp/jenkins-home" ./mvnw -v'
sh 'MAVEN_OPTS="-Duser.name=jenkins -Duser.home=/tmp/jenkins-home" ./mvnw -s settings.xml -Pci,artifactory ' +
'-Dartifactory.server=https://repo.spring.io ' +
"-Dartifactory.username=${ARTIFACTORY_USR} " +
"-Dartifactory.password=${ARTIFACTORY_PSW} " +
"-Dartifactory.staging-repository=libs-snapshot-local " +
"-Dartifactory.build-name=spring-data-mongodb " +
"-Dartifactory.build-number=${BUILD_NUMBER} " +
'-Dmaven.test.skip=true clean deploy -U -B'
}
}
}
}
}
post {
changed {
script {
slackSend(
color: (currentBuild.currentResult == 'SUCCESS') ? 'good' : 'danger',
channel: '#spring-data-dev',
message: "${currentBuild.fullDisplayName} - `${currentBuild.currentResult}`\n${env.BUILD_URL}")
emailext(
subject: "[${currentBuild.fullDisplayName}] ${currentBuild.currentResult}",
mimeType: 'text/html',
recipientProviders: [[$class: 'CulpritsRecipientProvider'], [$class: 'RequesterRecipientProvider']],
body: "<a href=\"${env.BUILD_URL}\">${currentBuild.fullDisplayName} is reported as ${currentBuild.currentResult}</a>")
}
}
}
}

202
LICENSE.txt Normal file
View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -1,73 +1,22 @@
image:https://spring.io/badges/spring-data-mongodb/ga.svg[Spring Data MongoDB,link=https://projects.spring.io/spring-data-mongodb#quick-start]
image:https://spring.io/badges/spring-data-mongodb/snapshot.svg[Spring Data MongoDB,link=https://projects.spring.io/spring-data-mongodb#quick-start]
image:https://spring.io/badges/spring-data-mongodb/ga.svg[Spring Data MongoDB,link=https://spring.io/projects/spring-data-mongodb#quick-start] image:https://spring.io/badges/spring-data-mongodb/snapshot.svg[Spring Data MongoDB,link=https://spring.io/projects/spring-data-mongodb#quick-start]
image:https://jenkins.spring.io/buildStatus/icon?job=spring-data-mongodb%2Fmaster&subject=Moore%20(master)[link=https://jenkins.spring.io/view/SpringData/job/spring-data-mongodb/]
image:https://jenkins.spring.io/buildStatus/icon?job=spring-data-mongodb%2F2.1.x&subject=Lovelace%20(2.1.x)[link=https://jenkins.spring.io/view/SpringData/job/spring-data-mongodb/]
image:https://jenkins.spring.io/buildStatus/icon?job=spring-data-mongodb%2F1.10.x&subject=Ingalls%20(1.10.x)[link=https://jenkins.spring.io/view/SpringData/job/spring-data-mongodb/]
= Spring Data MongoDB image:https://jenkins.spring.io/buildStatus/icon?job=spring-data-mongodb%2Fmain&subject=Build[link=https://jenkins.spring.io/view/SpringData/job/spring-data-mongodb/] https://gitter.im/spring-projects/spring-data[image:https://badges.gitter.im/spring-projects/spring-data.svg[Gitter]]
= Spring Data MongoDB
The primary goal of the https://spring.io/projects/spring-data[Spring Data] project is to make it easier to build Spring-powered applications that use new data access technologies such as non-relational databases, map-reduce frameworks, and cloud based data services.
The primary goal of the https://projects.spring.io/spring-data[Spring Data] project is to make it easier to build Spring-powered applications that use new data access technologies such as non-relational databases, map-reduce frameworks, and cloud based data services.
The Spring Data MongoDB project aims to provide a familiar and consistent Spring-based programming model for new datastores while retaining store-specific features and capabilities.
The Spring Data MongoDB project provides integration with the MongoDB document database.
Key functional areas of Spring Data MongoDB are a POJO centric model for interacting with a MongoDB `+Document+` and easily writing a repository style data access layer.
The Spring Data MongoDB project aims to provide a familiar and consistent Spring-based programming model for new datastores while retaining store-specific features and capabilities. The Spring Data MongoDB project provides integration with the MongoDB document database. Key functional areas of Spring Data MongoDB are a POJO centric model for interacting with a MongoDB DBCollection and easily writing a repository style data access layer.
[[code-of-conduct]]
== Code of Conduct
== Getting Help
This project is governed by the https://github.com/spring-projects/.github/blob/e3cc2ff230d8f1dca06535aa6b5a4a23815861d4/CODE_OF_CONDUCT.md[Spring Code of Conduct]. By participating, you are expected to uphold this code of conduct. Please report unacceptable behavior to spring-code-of-conduct@pivotal.io.
For a comprehensive treatment of all the Spring Data MongoDB features, please refer to:
[[getting-started]]
== Getting Started
* the https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/[User Guide]
* the https://docs.spring.io/spring-data/mongodb/docs/current/api/[JavaDocs] have extensive comments in them as well.
* the home page of https://projects.spring.io/spring-data-mongodb[Spring Data MongoDB] contains links to articles and other resources.
* for more detailed questions, use https://stackoverflow.com/questions/tagged/spring-data-mongodb[Spring Data Mongodb on Stackoverflow].
If you are new to Spring as well as to Spring Data, look for information about https://projects.spring.io/[Spring projects].
== Quick Start
=== Maven configuration
Add the Maven dependency:
[source,xml]
----
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${version}.RELEASE</version>
</dependency>
----
If you'd rather like the latest snapshots of the upcoming major version, use our Maven snapshot repository and declare the appropriate dependency version.
[source,xml]
----
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${version}.BUILD-SNAPSHOT</version>
</dependency>
<repository>
<id>spring-libs-snapshot</id>
<name>Spring Snapshot Repository</name>
<url>https://repo.spring.io/libs-snapshot</url>
</repository>
----
=== MongoTemplate
MongoTemplate is the central support class for Mongo database operations. It provides:
* Basic POJO mapping support to and from BSON
* Convenience methods to interact with the store (insert object, update objects) and MongoDB specific ones (geo-spatial operations, upserts, map-reduce etc.)
* Connection affinity callback
* Exception translation into Spring's https://docs.spring.io/spring/docs/current/spring-framework-reference/html/dao.html#dao-exceptions[technology agnostic DAO exception hierarchy].
=== Spring Data repositories
To simplify the creation of data repositories Spring Data MongoDB provides a generic repository programming model. It will automatically create a repository proxy for you that adds implementations of finder methods you specify on an interface.
For example, given a `Person` class with first and last name properties, a `PersonRepository` interface that can query for `Person` by last name and when the first name matches a like expression is shown below:
Here is a quick teaser of an application using Spring Data Repositories in Java:
[source,java]
----
@@ -77,22 +26,33 @@ public interface PersonRepository extends CrudRepository<Person, Long> {
List<Person> findByFirstnameLike(String firstname);
}
----
The queries issued on execution will be derived from the method name. Extending `CrudRepository` causes CRUD methods being pulled into the interface so that you can easily save and find single entities and collections of them.
@Service
public class MyService {
You can have Spring automatically create a proxy for the interface by using the following JavaConfig:
private final PersonRepository repository;
public MyService(PersonRepository repository) {
this.repository = repository;
}
public void doWork() {
repository.deleteAll();
Person person = new Person();
person.setFirstname("Oliver");
person.setLastname("Gierke");
repository.save(person);
List<Person> lastNameResults = repository.findByLastname("Gierke");
List<Person> firstNameResults = repository.findByFirstnameLike("Oli*");
}
}
[source,java]
----
@Configuration
@EnableMongoRepositories
class ApplicationConfig extends AbstractMongoConfiguration {
@Override
public MongoClient mongoClient() throws Exception {
return new MongoClient();
}
class ApplicationConfig extends AbstractMongoClientConfiguration {
@Override
protected String getDatabaseName() {
@@ -101,134 +61,172 @@ class ApplicationConfig extends AbstractMongoConfiguration {
}
----
This sets up a connection to a local MongoDB instance and enables the detection of Spring Data repositories (through `@EnableMongoRepositories`). The same configuration would look like this in XML:
[[maven-configuration]]
=== Maven configuration
Add the Maven dependency:
[source,xml]
----
<bean id="template" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg>
<bean class="com.mongodb.MongoClient">
<constructor-arg value="localhost" />
<constructor-arg value="27017" />
</bean>
</constructor-arg>
<constructor-arg value="database" />
</bean>
<mongo:repositories base-package="com.acme.repository" />
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${version}</version>
</dependency>
----
This will find the repository interface and register a proxy object in the container. You can use it as shown below:
If you'd rather like the latest snapshots of the upcoming major version, use our Maven snapshot repository
and declare the appropriate dependency version.
[source,java]
[source,xml]
----
@Service
public class MyService {
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${version}-SNAPSHOT</version>
</dependency>
private final PersonRepository repository;
@Autowired
public MyService(PersonRepository repository) {
this.repository = repository;
}
public void doWork() {
repository.deleteAll();
Person person = new Person();
person.setFirstname("Oliver");
person.setLastname("Gierke");
person = repository.save(person);
List<Person> lastNameResults = repository.findByLastname("Gierke");
List<Person> firstNameResults = repository.findByFirstnameLike("Oli*");
}
}
<repository>
<id>spring-snapshot</id>
<name>Spring Snapshot Repository</name>
<url>https://repo.spring.io/snapshot</url>
</repository>
----
=== MongoDB 4.0 Transactions
[[upgrading]]
== Upgrading
As of version 4 MongoDB supports https://www.mongodb.com/transactions[Transactions]. Transactions are built on top of
`ClientSessions` and therefore require an active session.
Instructions for how to upgrade from earlier versions of Spring Data are provided on the project https://github.com/spring-projects/spring-data-commons/wiki[wiki].
Follow the links in the https://github.com/spring-projects/spring-data-commons/wiki#release-notes[release notes section] to find the version that you want to upgrade to.
`MongoTransactionManager` is the gateway to the well known Spring transaction support. It allows applications to use
https://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html[managed transaction features of Spring].
The `MongoTransactionManager` binds a `ClientSession` to the thread. `MongoTemplate` automatically detects those and operates on them accordingly.
[[getting-help]]
== Getting Help
[source,java]
Having trouble with Spring Data? Wed love to help!
* Check the
https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/[reference documentation], and https://docs.spring.io/spring-data/mongodb/docs/current/api/[Javadocs].
* Learn the Spring basics Spring Data builds on Spring Framework, check the https://spring.io[spring.io] web-site for a wealth of reference documentation.
If you are just starting out with Spring, try one of the https://spring.io/guides[guides].
* If you are upgrading, check out the https://docs.spring.io/spring-data/mongodb/docs/current/changelog.txt[changelog] for "`new and noteworthy`" features.
* Ask a question - we monitor https://stackoverflow.com[stackoverflow.com] for questions tagged with https://stackoverflow.com/tags/spring-data[`spring-data-mongodb`].
You can also chat with the community on https://gitter.im/spring-projects/spring-data[Gitter].
* Report bugs with Spring Data MongoDB at https://github.com/spring-projects/spring-data-mongodb/issues[github.com/spring-projects/spring-data-mongodb/issues].
[[reporting-issues]]
== Reporting Issues
Spring Data uses Github as issue tracking system to record bugs and feature requests.
If you want to raise an issue, please follow the recommendations below:
* Before you log a bug, please search the https://github.com/spring-projects/spring-data-mongodb/issues[issue tracker] to see if someone has already reported the problem.
* If the issue does not already exist, https://github.com/spring-projects/spring-data-mongodb/issues/new[create a new issue].
* Please provide as much information as possible with the issue report, we like to know the version of Spring Data that you are using, the JVM version, Stacktrace, etc.
* If you need to paste code, or include a stack trace use https://guides.github.com/features/mastering-markdown/[Markdown] code fences +++```+++.
[[guides]]
== Guides
The https://spring.io/[spring.io] site contains several guides that show how to use Spring Data step-by-step:
* https://spring.io/guides/gs/accessing-data-mongodb/[Accessing Data with MongoDB] is a very basic guide that shows you how to create a simple application and how to access data using repositories.
* https://spring.io/guides/gs/accessing-mongodb-data-rest/[Accessing MongoDB Data with REST] is a guide to creating a REST web service exposing data stored in MongoDB through repositories.
[[examples]]
== Examples
* https://github.com/spring-projects/spring-data-examples/[Spring Data Examples] contains example projects that explain specific features in more detail.
[[building-from-source]]
== Building from Source
You do not need to build from source to use Spring Data. Binaries are available in https://repo.spring.io[repo.spring.io]
and accessible from Maven using the Maven configuration noted <<maven-configuration,above>>.
NOTE: Configuration for Gradle is similar to Maven.
The best way to get started is by creating a Spring Boot project using MongoDB on https://start.spring.io[start.spring.io].
Follow this https://start.spring.io/#type=maven-project&language=java&platformVersion=3.0.0&packaging=jar&jvmVersion=17&groupId=com.example&artifactId=demo&name=demo&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.demo&dependencies=data-mongodb[link]
to build an imperative application and this https://start.spring.io/#type=maven-project&language=java&platformVersion=3.0.0&packaging=jar&jvmVersion=17&groupId=com.example&artifactId=demo&name=demo&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.demo&dependencies=data-mongodb-reactive[link]
to build a reactive one.
However, if you want to try out the latest and greatest, Spring Data MongoDB can be easily built with the https://github.com/takari/maven-wrapper[Maven wrapper]
and minimally, JDK 17 (https://www.oracle.com/java/technologies/downloads/[JDK downloads]).
In order to build Spring Data MongoDB, you will need to https://www.mongodb.com/try/download/community[download]
and https://docs.mongodb.com/manual/installation/[install a MongoDB distribution].
Once you have installed MongoDB, you need to start a MongoDB server. It is convenient to set an environment variable to
your MongoDB installation directory (e.g. `MONGODB_HOME`).
To run the full test suite, a https://docs.mongodb.com/manual/tutorial/deploy-replica-set/[MongoDB Replica Set]
is required.
To run the MongoDB server enter the following command from a command-line:
[source,bash]
----
@Configuration
static class Config extends AbstractMongoConfiguration {
@Bean
MongoTransactionManager transactionManager(MongoDbFactory dbFactory) {
return new MongoTransactionManager(dbFactory);
}
// ...
}
@Component
public class StateService {
@Transactional
void someBusinessFunction(Step step) {
template.insert(step);
process(step);
template.update(Step.class).apply(Update.set("state", // ...
};
});
$ $MONGODB_HOME/bin/mongod --dbpath $MONGODB_HOME/runtime/data --ipv6 --port 27017 --replSet rs0
...
"msg":"Successfully connected to host"
----
== Contributing to Spring Data
Once the MongoDB server starts up, you should see the message (`msg`), "_Successfully connected to host_".
Here are some ways for you to get involved in the community:
Notice the `--dbpath` option to the `mongod` command. You can set this to anything you like, but in this case, we set
the absolute path to a sub-directory (`runtime/data/`) under the MongoDB installation directory (in `$MONGODB_HOME`).
* Get involved with the Spring community on Stackoverflow and help out on the https://stackoverflow.com/questions/tagged/spring-data-mongodb[spring-data-mongodb] tag by responding to questions and joining the debate.
* Create https://jira.spring.io/browse/DATAMONGO[JIRA] tickets for bugs and new features and comment and vote on the ones that you are interested in.
* Github is for social coding: if you want to write code, we encourage contributions through pull requests from https://help.github.com/forking/[forks of this repository]. If you want to contribute code this way, please reference a JIRA ticket as well covering the specific issue you are addressing.
* Watch for upcoming articles on Spring by https://spring.io/blog[subscribing] to spring.io.
You need to initialize the MongoDB replica set only once on the first time the MongoDB server is started.
To initialize the replica set, start a mongo client:
Before we accept a non-trivial patch or pull request we will need you to https://cla.pivotal.io/sign/spring[sign the Contributor License Agreement]. Signing the contributors agreement does not grant anyone commit rights to the main repository, but it does mean that we can accept your contributions, and you will get an author credit if we do. If you forget to do so, you'll be reminded when you submit a pull request. Active contributors might be asked to join the core team, and given the ability to merge pull requests.
[source,bash]
----
$ $MONGODB_HOME/bin/mongo
MongoDB server version: 6.0.0
...
----
== Running CI tasks locally
Then enter the following command:
Since this pipeline is purely Docker-based, it's easy to:
[source,bash]
----
mongo> rs.initiate({ _id: 'rs0', members: [ { _id: 0, host: '127.0.0.1:27017' } ] })
----
* Debug what went wrong on your local machine.
* Test out a a tweak to your test routine before sending it out.
* Experiment against a new image before submitting your pull request.
Finally, on UNIX-based system (for example, Linux or Mac OS X) you may need to adjust the `ulimit`.
In case you need to, you can adjust the `ulimit` with the following command (32768 is just a recommendation):
All of these use cases are great reasons to essentially run what the CI server does on your local machine.
[source,bash]
----
$ ulimit -n 32768
----
IMPORTANT: To do this you must have Docker installed on your machine.
You can use `ulimit -a` again to verify the `ulimit` for "_open files_" was set appropriately.
1. `docker run -it --mount type=bind,source="$(pwd)",target=/spring-data-mongodb-github springci/spring-data-openjdk8-with-mongodb-4.0:latest /bin/bash`
+
This will launch the Docker image and mount your source code at `spring-data-mongodb-github`.
+
2. `cd spring-data-mongodb-github`
+
Next, run the tests from inside the container:
+
3. `./mvnw clean dependency:list test -Dsort -Dbundlor.enabled=false -B` (or with whatever profile you need to test out)
Now you are ready to build Spring Data MongoDB. Simply enter the following `mvnw` (Maven Wrapper) command:
Since the container is binding to your source, you can make edits from your IDE and continue to run build jobs.
[source,bash]
----
$ ./mvnw clean install
----
If you need to package things up, do this:
If you want to build with the regular `mvn` command, you will need https://maven.apache.org/run-maven/index.html[Maven v3.8.0 or above].
1. `docker run -it --mount type=bind,source="$(pwd)",target=/spring-data-mongodb-github springci/spring-data-openjdk8-with-mongodb-4.0:latest /bin/bash`
+
This will launch the Docker image and mount your source code at `spring-data-mongodb-github`.
+
2. `cd spring-data-mongodb-github`
+
Next, package things from inside the container doing this:
+
3. `./mvnw clean dependency:list package -Dsort -Dbundlor.enabled=false -B`
_Also see link:CONTRIBUTING.adoc[CONTRIBUTING.adoc] if you wish to submit pull requests, and in particular, please sign
the https://cla.pivotal.io/sign/spring[Contributors Agreement] before your first non-trivial change._
NOTE: Docker containers can eat up disk space fast! From time to time, run `docker system prune` to clean out old images.
=== Building reference documentation
Building the documentation builds also the project without running tests.
[source,bash]
----
$ ./mvnw clean install -Pdistribute
----
The generated documentation is available from `target/site/reference/html/index.html`.
[[license]]
== License
Spring Data MongoDB is Open Source software released under the https://www.apache.org/licenses/LICENSE-2.0.html[Apache 2.0 license].

View File

@@ -0,0 +1,22 @@
ARG BASE
FROM ${BASE}
# Any ARG statements before FROM are cleared.
ARG MONGODB
ENV TZ=Etc/UTC
ENV DEBIAN_FRONTEND=noninteractive
RUN set -eux; \
sed -i -e 's/archive.ubuntu.com/mirror.one.com/g' /etc/apt/sources.list && \
sed -i -e 's/security.ubuntu.com/mirror.one.com/g' /etc/apt/sources.list && \
sed -i -e 's/ports.ubuntu.com/mirrors.ocf.berkeley.edu/g' /etc/apt/sources.list && \
sed -i -e 's/http/https/g' /etc/apt/sources.list && \
apt-get update && apt-get install -y apt-transport-https apt-utils gnupg2 && \
apt-key adv --keyserver hkps://keyserver.ubuntu.com:443 --recv 656408E390CFB1F5 && \
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-4.4.list && \
echo ${TZ} > /etc/timezone
RUN apt-get update && \
apt-get install -y mongodb-org=${MONGODB} mongodb-org-server=${MONGODB} mongodb-org-shell=${MONGODB} mongodb-org-mongos=${MONGODB} mongodb-org-tools=${MONGODB} && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*

View File

@@ -0,0 +1,24 @@
ARG BASE
FROM ${BASE}
# Any ARG statements before FROM are cleared.
ARG MONGODB
ENV TZ=Etc/UTC
ENV DEBIAN_FRONTEND=noninteractive
RUN set -eux; \
sed -i -e 's/archive.ubuntu.com/mirror.one.com/g' /etc/apt/sources.list && \
sed -i -e 's/security.ubuntu.com/mirror.one.com/g' /etc/apt/sources.list && \
sed -i -e 's/ports.ubuntu.com/mirrors.ocf.berkeley.edu/g' /etc/apt/sources.list && \
sed -i -e 's/http/https/g' /etc/apt/sources.list && \
apt-get update && apt-get install -y apt-transport-https apt-utils gnupg2 wget && \
# MongoDB 5.0 release signing key
apt-key adv --keyserver hkps://keyserver.ubuntu.com:443 --recv B00A0BD1E2C63C11 && \
# Needed when MongoDB creates a 5.0 folder.
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-5.0.list && \
echo ${TZ} > /etc/timezone
RUN apt-get update && \
apt-get install -y mongodb-org=${MONGODB} mongodb-org-server=${MONGODB} mongodb-org-shell=${MONGODB} mongodb-org-mongos=${MONGODB} mongodb-org-tools=${MONGODB} && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*

View File

@@ -0,0 +1,24 @@
ARG BASE
FROM ${BASE}
# Any ARG statements before FROM are cleared.
ARG MONGODB
ENV TZ=Etc/UTC
ENV DEBIAN_FRONTEND=noninteractive
RUN set -eux; \
sed -i -e 's/archive.ubuntu.com/mirror.one.com/g' /etc/apt/sources.list && \
sed -i -e 's/security.ubuntu.com/mirror.one.com/g' /etc/apt/sources.list && \
sed -i -e 's/ports.ubuntu.com/mirrors.ocf.berkeley.edu/g' /etc/apt/sources.list && \
sed -i -e 's/http/https/g' /etc/apt/sources.list && \
apt-get update && apt-get install -y apt-transport-https apt-utils gnupg2 wget && \
# MongoDB 6.0 release signing key
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | apt-key add - && \
# Needed when MongoDB creates a 6.0 folder.
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-6.0.list && \
echo ${TZ} > /etc/timezone
RUN apt-get update && \
apt-get install -y mongodb-org=${MONGODB} mongodb-org-server=${MONGODB} mongodb-org-shell=${MONGODB} mongodb-org-mongos=${MONGODB} mongodb-org-tools=${MONGODB} && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*

View File

@@ -1,14 +0,0 @@
FROM adoptopenjdk/openjdk8:latest
RUN apt-get update && apt-get install -y apt-transport-https apt-utils gnupg2
RUN apt-key adv --keyserver hkps://keyserver.ubuntu.com:443 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
RUN echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-4.0.list
RUN apt-get update
RUN apt-get install -y mongodb-org=4.0.9 mongodb-org-server=4.0.9 mongodb-org-shell=4.0.9 mongodb-org-mongos=4.0.9 mongodb-org-tools=4.0.9
RUN apt-get clean \
&& rm -rf /var/lib/apt/lists/*

View File

@@ -1,14 +0,0 @@
FROM adoptopenjdk/openjdk8:latest
RUN apt-get update && apt-get install -y apt-transport-https apt-utils gnupg2
RUN apt-key adv --keyserver hkps://keyserver.ubuntu.com:443 --recv 4B7C549A058F8B6B
RUN echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.1 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-4.1.list
RUN apt-get update
RUN apt-get install -y mongodb-org-unstable=4.1.13 mongodb-org-unstable-server=4.1.13 mongodb-org-unstable-shell=4.1.13 mongodb-org-unstable-mongos=4.1.13 mongodb-org-unstable-tools=4.1.13
RUN apt-get clean \
&& rm -rf /var/lib/apt/lists/*

25
ci/pipeline.properties Normal file
View File

@@ -0,0 +1,25 @@
# Java versions
java.main.tag=17.0.5_8-jdk-focal
# Docker container images - standard
docker.java.main.image=harbor-repo.vmware.com/dockerhub-proxy-cache/library/eclipse-temurin:${java.main.tag}
# Supported versions of MongoDB
docker.mongodb.4.4.version=4.4.17
docker.mongodb.5.0.version=5.0.13
docker.mongodb.6.0.version=6.0.2
# Supported versions of Redis
docker.redis.6.version=6.2.6
# Supported versions of Cassandra
docker.cassandra.3.version=3.11.14
# Docker environment settings
docker.java.inside.basic=-v $HOME:/tmp/jenkins-home
docker.java.inside.docker=-u root -v /var/run/docker.sock:/var/run/docker.sock -v /usr/bin/docker:/usr/bin/docker -v $HOME:/tmp/jenkins-home
# Credentials
docker.registry=
docker.credentials=hub.docker.com-springbuildmaster
artifactory.credentials=02bd1690-b54f-4c9f-819d-a77cb7a9822c

97
pom.xml
View File

@@ -5,17 +5,17 @@
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>2.2.0.RC1</version>
<version>4.1.x-MANUAL-ENCRYPTION-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Spring Data MongoDB</name>
<description>MongoDB support for Spring Data</description>
<url>https://projects.spring.io/spring-data-mongodb</url>
<url>https://spring.io/projects/spring-data-mongodb</url>
<parent>
<groupId>org.springframework.data.build</groupId>
<artifactId>spring-data-parent</artifactId>
<version>2.2.0.RC1</version>
<version>3.1.0-SNAPSHOT</version>
</parent>
<modules>
@@ -26,9 +26,9 @@
<properties>
<project.type>multi</project.type>
<dist.id>spring-data-mongodb</dist.id>
<springdata.commons>2.2.0.RC1</springdata.commons>
<mongo>3.11.0-beta3</mongo>
<mongo.reactivestreams>1.11.0</mongo.reactivestreams>
<springdata.commons>3.1.0-SNAPSHOT</springdata.commons>
<mongo>4.8.2</mongo>
<mongo.reactivestreams>${mongo}</mongo.reactivestreams>
<jmh.version>1.19</jmh.version>
</properties>
@@ -112,61 +112,18 @@
</developer>
</developers>
<scm>
<connection>scm:git:https://github.com/spring-projects/spring-data-mongodb.git</connection>
<developerConnection>scm:git:git@github.com:spring-projects/spring-data-mongodb.git</developerConnection>
<url>https://github.com/spring-projects/spring-data-mongodb</url>
</scm>
<issueManagement>
<system>GitHub</system>
<url>https://github.com/spring-projects/spring-data-mongodb/issues</url>
</issueManagement>
<profiles>
<profile>
<id>snapshot</id>
<build>
<plugins>
<plugin>
<groupId>org.jfrog.buildinfo</groupId>
<artifactId>artifactory-maven-plugin</artifactId>
<version>2.6.1</version>
<inherited>false</inherited>
<executions>
<execution>
<id>build-info</id>
<goals>
<goal>publish</goal>
</goals>
<configuration>
<buildInfo>
<buildUrl>{{BUILD_URL}}</buildUrl>
</buildInfo>
<deployProperties>
<zip.name>spring-data-mongodb</zip.name>
<zip.displayname>spring-data-mongodb</zip.displayname>
<zip.deployed>false</zip.deployed>
<archives>*:*:*:*@zip</archives>
</deployProperties>
<publisher>
<contextUrl>https://repo.spring.io</contextUrl>
<username>{{ARTIFACTORY_USR}}</username>
<password>{{ARTIFACTORY_PSW}}</password>
<repoKey>libs-snapshot-local</repoKey>
<snapshotRepoKey>libs-snapshot-local</snapshotRepoKey>
</publisher>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>release</id>
<build>
<plugins>
<plugin>
<groupId>org.jfrog.buildinfo</groupId>
<artifactId>artifactory-maven-plugin</artifactId>
<inherited>false</inherited>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>benchmarks</id>
<modules>
@@ -181,15 +138,28 @@
<!-- MongoDB -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<artifactId>mongodb-driver-core</artifactId>
<version>${mongo}</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-libs-milestone</id>
<url>https://repo.spring.io/libs-milestone</url>
<id>spring-libs-snapshot</id>
<url>https://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>sonatype-libs-snapshot</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
@@ -202,7 +172,6 @@
<id>spring-libs-milestone</id>
<url>https://repo.spring.io/libs-milestone</url>
</pluginRepository>
</pluginRepositories>
</project>

29
settings.xml Normal file
View File

@@ -0,0 +1,29 @@
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
https://maven.apache.org/xsd/settings-1.0.0.xsd">
<servers>
<server>
<id>spring-plugins-release</id>
<username>${env.ARTIFACTORY_USR}</username>
<password>${env.ARTIFACTORY_PSW}</password>
</server>
<server>
<id>spring-libs-snapshot</id>
<username>${env.ARTIFACTORY_USR}</username>
<password>${env.ARTIFACTORY_PSW}</password>
</server>
<server>
<id>spring-libs-milestone</id>
<username>${env.ARTIFACTORY_USR}</username>
<password>${env.ARTIFACTORY_PSW}</password>
</server>
<server>
<id>spring-libs-release</id>
<username>${env.ARTIFACTORY_USR}</username>
<password>${env.ARTIFACTORY_PSW}</password>
</server>
</servers>
</settings>

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>2.2.0.RC1</version>
<version>4.1.x-MANUAL-ENCRYPTION-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017-2019 the original author or authors.
* Copyright 2017-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017-2019 the original author or authors.
* Copyright 2017-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017-2019 the original author or authors.
* Copyright 2017-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017-2019 the original author or authors.
* Copyright 2017-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -322,7 +322,7 @@ public class AbstractMicrobenchmark {
try {
ResultsWriter.forUri(uri).write(results);
} catch (Exception e) {
System.err.println(String.format("Cannot save benchmark results to '%s'. Error was %s.", uri, e));
System.err.println(String.format("Cannot save benchmark results to '%s'; Error was %s", uri, e));
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017-2019 the original author or authors.
* Copyright 2017-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017-2019 the original author or authors.
* Copyright 2017-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017-2019 the original author or authors.
* Copyright 2017-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
@@ -14,7 +15,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>2.2.0.RC1</version>
<version>4.1.x-MANUAL-ENCRYPTION-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
@@ -29,16 +30,13 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>wagon-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<configuration>
<attributes>
<mongo-reactivestreams>${mongo.reactivestreams}</mongo-reactivestreams>
<mongo-reactivestreams>${mongo.reactivestreams}
</mongo-reactivestreams>
<reactor>${reactor}</reactor>
</attributes>
</configuration>
@@ -47,4 +45,15 @@
</build>
<pluginRepositories>
<pluginRepository>
<id>spring-plugins-release</id>
<url>https://repo.spring.io/plugins-release</url>
</pluginRepository>
<pluginRepository>
<id>spring-plugins-snapshot</id>
<url>https://repo.spring.io/libs-snapshot</url>
</pluginRepository>
</pluginRepositories>
</project>

View File

@@ -1,5 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
@@ -11,7 +13,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>2.2.0.RC1</version>
<version>4.1.x-MANUAL-ENCRYPTION-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
@@ -65,6 +67,12 @@
<artifactId>querydsl-mongodb</artifactId>
<version>${querydsl}</version>
<optional>true</optional>
<exclusions>
<exclusion>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
@@ -81,7 +89,22 @@
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
<optional>true</optional>
</dependency>
<!-- reactive -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>${mongo}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-reactivestreams</artifactId>
@@ -91,19 +114,9 @@
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-async</artifactId>
<version>${mongo}</version>
<artifactId>mongodb-crypt</artifactId>
<version>1.6.1</version>
<optional>true</optional>
<exclusions>
<exclusion>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
@@ -119,34 +132,14 @@
</dependency>
<dependency>
<groupId>io.reactivex</groupId>
<groupId>io.reactivex.rxjava3</groupId>
<artifactId>rxjava</artifactId>
<version>${rxjava}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.reactivex</groupId>
<artifactId>rxjava-reactive-streams</artifactId>
<version>${rxjava-reactive-streams}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.reactivex.rxjava2</groupId>
<artifactId>rxjava</artifactId>
<version>${rxjava2}</version>
<version>${rxjava3}</version>
<optional>true</optional>
</dependency>
<!-- CDI -->
<!-- Dependency order required to build against CDI 1.0 and test with CDI 2.0 -->
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jcdi_2.0_spec</artifactId>
<version>1.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.interceptor</groupId>
@@ -156,31 +149,48 @@
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<groupId>jakarta.enterprise</groupId>
<artifactId>jakarta.enterprise.cdi-api</artifactId>
<version>${cdi}</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>${javax-annotation-api}</version>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>${jakarta-annotation-api}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.openwebbeans</groupId>
<artifactId>openwebbeans-se</artifactId>
<classifier>jakarta</classifier>
<version>${webbeans}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.openwebbeans</groupId>
<artifactId>openwebbeans-spi</artifactId>
<classifier>jakarta</classifier>
<version>${webbeans}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.openwebbeans</groupId>
<artifactId>openwebbeans-impl</artifactId>
<classifier>jakarta</classifier>
<version>${webbeans}</version>
<scope>test</scope>
</dependency>
<!-- JSR 303 Validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<version>${validation}</version>
<optional>true</optional>
</dependency>
@@ -193,23 +203,37 @@
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-observation</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-tracing</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
<version>7.0.1.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime}</version>
<scope>test</scope>
<groupId>jakarta.el</groupId>
<artifactId>jakarta.el-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.threeten</groupId>
<artifactId>threetenbp</artifactId>
<version>${threetenbp}</version>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.el</artifactId>
<version>4.0.2</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
@@ -219,13 +243,6 @@
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>${slf4j}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>nl.jqno.equalsverifier</groupId>
<artifactId>equalsverifier</artifactId>
@@ -254,9 +271,16 @@
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
<groupId>org.junit-pioneer</groupId>
<artifactId>junit-pioneer</artifactId>
<version>0.5.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jakarta.transaction</groupId>
<artifactId>jakarta.transaction-api</artifactId>
<version>2.0.0</version>
<scope>test</scope>
</dependency>
@@ -276,24 +300,54 @@
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-core</artifactId>
<version>${kotlin-coroutines}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-reactor</artifactId>
<version>${kotlin-coroutines}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.mockk</groupId>
<artifactId>mockk</artifactId>
<artifactId>mockk-jvm</artifactId>
<version>${mockk}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-jre8-standalone</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-tracing-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-tracing-integration-test</artifactId>
<scope>test</scope>
</dependency>
<!-- jMolecules -->
<dependency>
<groupId>org.jmolecules</groupId>
<artifactId>jmolecules-ddd</artifactId>
<version>${jmolecules}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@@ -318,8 +372,11 @@
<goal>test-process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-test-sources</outputDirectory>
<processor>org.springframework.data.mongodb.repository.support.MongoAnnotationProcessor</processor>
<outputDirectory>target/generated-test-sources
</outputDirectory>
<processor>
org.springframework.data.mongodb.repository.support.MongoAnnotationProcessor
</processor>
</configuration>
</execution>
</executions>
@@ -339,15 +396,11 @@
<exclude>**/ReactivePerformanceTests.java</exclude>
</excludes>
<systemPropertyVariables>
<java.util.logging.config.file>src/test/resources/logging.properties</java.util.logging.config.file>
<java.util.logging.config.file>
src/test/resources/logging.properties
</java.util.logging.config.file>
<reactor.trace.cancel>true</reactor.trace.cancel>
</systemPropertyVariables>
<properties>
<property>
<name>listener</name>
<value>org.springframework.data.mongodb.test.util.CleanMongoDBJunitRunListener</value>
</property>
</properties>
</configuration>
</plugin>

View File

@@ -0,0 +1,144 @@
/*
* Copyright 2021-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb;
import java.util.Arrays;
import org.bson.Document;
import org.bson.codecs.DocumentCodec;
import org.bson.codecs.configuration.CodecRegistry;
import org.springframework.data.mongodb.util.json.ParameterBindingDocumentCodec;
import org.springframework.data.util.Lazy;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* A {@link MongoExpression} using the {@link ParameterBindingDocumentCodec} for parsing a raw ({@literal json})
* expression. The expression will be wrapped within <code>{ ... }</code> if necessary. The actual parsing and parameter
* binding of placeholders like {@code ?0} is delayed upon first call on the the target {@link Document} via
* {@link #toDocument()}.
* <br />
*
* <pre class="code">
* $toUpper : $name -> { '$toUpper' : '$name' }
*
* { '$toUpper' : '$name' } -> { '$toUpper' : '$name' }
*
* { '$toUpper' : '?0' }, "$name" -> { '$toUpper' : '$name' }
* </pre>
*
* Some types might require a special {@link org.bson.codecs.Codec}. If so, make sure to provide a {@link CodecRegistry}
* containing the required {@link org.bson.codecs.Codec codec} via {@link #withCodecRegistry(CodecRegistry)}.
*
* @author Christoph Strobl
* @since 3.2
*/
public class BindableMongoExpression implements MongoExpression {
private final String expressionString;
private final @Nullable CodecRegistryProvider codecRegistryProvider;
private final @Nullable Object[] args;
private final Lazy<Document> target;
/**
* Create a new instance of {@link BindableMongoExpression}.
*
* @param expression must not be {@literal null}.
* @param args can be {@literal null}.
*/
public BindableMongoExpression(String expression, @Nullable Object[] args) {
this(expression, null, args);
}
/**
* Create a new instance of {@link BindableMongoExpression}.
*
* @param expression must not be {@literal null}.
* @param codecRegistryProvider can be {@literal null}.
* @param args can be {@literal null}.
*/
public BindableMongoExpression(String expression, @Nullable CodecRegistryProvider codecRegistryProvider,
@Nullable Object[] args) {
this.expressionString = expression;
this.codecRegistryProvider = codecRegistryProvider;
this.args = args;
this.target = Lazy.of(this::parse);
}
/**
* Provide the {@link CodecRegistry} used to convert expressions.
*
* @param codecRegistry must not be {@literal null}.
* @return new instance of {@link BindableMongoExpression}.
*/
public BindableMongoExpression withCodecRegistry(CodecRegistry codecRegistry) {
return new BindableMongoExpression(expressionString, () -> codecRegistry, args);
}
/**
* Provide the arguments to bind to the placeholders via their index.
*
* @param args must not be {@literal null}.
* @return new instance of {@link BindableMongoExpression}.
*/
public BindableMongoExpression bind(Object... args) {
return new BindableMongoExpression(expressionString, codecRegistryProvider, args);
}
@Override
public Document toDocument() {
return target.get();
}
@Override
public String toString() {
return "BindableMongoExpression{" + "expressionString='" + expressionString + '\'' + ", args="
+ Arrays.toString(args) + '}';
}
private Document parse() {
String expression = wrapJsonIfNecessary(expressionString);
if (ObjectUtils.isEmpty(args)) {
if (codecRegistryProvider == null) {
return Document.parse(expression);
}
return Document.parse(expression, codecRegistryProvider.getCodecFor(Document.class)
.orElseGet(() -> new DocumentCodec(codecRegistryProvider.getCodecRegistry())));
}
ParameterBindingDocumentCodec codec = codecRegistryProvider == null ? new ParameterBindingDocumentCodec()
: new ParameterBindingDocumentCodec(codecRegistryProvider.getCodecRegistry());
return codec.decode(expression, args);
}
private static String wrapJsonIfNecessary(String json) {
if (StringUtils.hasText(json) && (json.startsWith("{") && json.endsWith("}"))) {
return json;
}
return "{" + json + "}";
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2019 the original author or authors.
* Copyright 2015-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,9 +19,9 @@ import java.util.List;
import org.springframework.dao.DataAccessException;
import com.mongodb.BulkWriteError;
import com.mongodb.BulkWriteException;
import com.mongodb.BulkWriteResult;
import com.mongodb.MongoBulkWriteException;
import com.mongodb.bulk.BulkWriteError;
import com.mongodb.bulk.BulkWriteResult;
/**
* Is thrown when errors occur during bulk operations.
@@ -38,12 +38,12 @@ public class BulkOperationException extends DataAccessException {
private final BulkWriteResult result;
/**
* Creates a new {@link BulkOperationException} with the given message and source {@link BulkWriteException}.
* Creates a new {@link BulkOperationException} with the given message and source {@link MongoBulkWriteException}.
*
* @param message must not be {@literal null}.
* @param source must not be {@literal null}.
*/
public BulkOperationException(String message, BulkWriteException source) {
public BulkOperationException(String message, MongoBulkWriteException source) {
super(message, source);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018-2019 the original author or authors.
* Copyright 2018-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017-2019 the original author or authors.
* Copyright 2017-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -62,7 +62,7 @@ public interface CodecRegistryProvider {
*/
default <T> Optional<Codec<T>> getCodecFor(Class<T> type) {
Assert.notNull(type, "Type must not be null!");
Assert.notNull(type, "Type must not be null");
try {
return Optional.of(getCodecRegistry().get(type));

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2019 the original author or authors.
* Copyright 2010-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2019 the original author or authors.
* Copyright 2013-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,8 +25,10 @@ public class LazyLoadingException extends UncategorizedDataAccessException {
private static final long serialVersionUID = -7089224903873220037L;
/**
* @param msg
* @param cause
* Constructor for LazyLoadingException.
*
* @param msg the detail message.
* @param cause the exception thrown by underlying data access API.
*/
public LazyLoadingException(String msg, Throwable cause) {
super(msg, cause);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2019 the original author or authors.
* Copyright 2011-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,8 +20,8 @@ import org.springframework.util.StringUtils;
/**
* Helper class featuring helper methods for working with MongoDb collections.
* <p/>
* <p/>
* <br />
* <br />
* Mainly intended for internal use within the framework.
*
* @author Thomas Risberg

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2019 the original author or authors.
* Copyright 2011-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,7 +21,6 @@ import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.data.mongodb.core.MongoExceptionTranslator;
import com.mongodb.ClientSessionOptions;
import com.mongodb.DB;
import com.mongodb.client.ClientSession;
import com.mongodb.client.MongoDatabase;
@@ -31,25 +30,26 @@ import com.mongodb.client.MongoDatabase;
* @author Mark Pollack
* @author Thomas Darimont
* @author Christoph Strobl
* @since 3.0
*/
public interface MongoDbFactory extends CodecRegistryProvider, MongoSessionProvider {
public interface MongoDatabaseFactory extends CodecRegistryProvider, MongoSessionProvider {
/**
* Creates a default {@link MongoDatabase} instance.
* Obtain a {@link MongoDatabase} from the underlying factory.
*
* @return
* @return never {@literal null}.
* @throws DataAccessException
*/
MongoDatabase getDb() throws DataAccessException;
MongoDatabase getMongoDatabase() throws DataAccessException;
/**
* Creates a {@link DB} instance to access the database with the given name.
* Obtain a {@link MongoDatabase} instance to access the database with the given name.
*
* @param dbName must not be {@literal null} or empty.
* @return
* @param dbName must not be {@literal null}.
* @return never {@literal null}.
* @throws DataAccessException
*/
MongoDatabase getDb(String dbName) throws DataAccessException;
MongoDatabase getMongoDatabase(String dbName) throws DataAccessException;
/**
* Exposes a shared {@link MongoExceptionTranslator}.
@@ -58,16 +58,6 @@ public interface MongoDbFactory extends CodecRegistryProvider, MongoSessionProvi
*/
PersistenceExceptionTranslator getExceptionTranslator();
/**
* Get the legacy database entry point. Please consider {@link #getDb()} instead.
*
* @return
* @deprecated since 2.1, use {@link #getDb()}. This method will be removed with a future version as it works only
* with the legacy MongoDB driver.
*/
@Deprecated
DB getLegacyDb();
/**
* Get the underlying {@link CodecRegistry} used by the MongoDB Java driver.
*
@@ -75,7 +65,7 @@ public interface MongoDbFactory extends CodecRegistryProvider, MongoSessionProvi
*/
@Override
default CodecRegistry getCodecRegistry() {
return getDb().getCodecRegistry();
return getMongoDatabase().getCodecRegistry();
}
/**
@@ -88,29 +78,29 @@ public interface MongoDbFactory extends CodecRegistryProvider, MongoSessionProvi
ClientSession getSession(ClientSessionOptions options);
/**
* Obtain a {@link ClientSession} bound instance of {@link MongoDbFactory} returning {@link MongoDatabase} instances
* that are aware and bound to a new session with given {@link ClientSessionOptions options}.
* Obtain a {@link ClientSession} bound instance of {@link MongoDatabaseFactory} returning {@link MongoDatabase}
* instances that are aware and bound to a new session with given {@link ClientSessionOptions options}.
*
* @param options must not be {@literal null}.
* @return never {@literal null}.
* @since 2.1
*/
default MongoDbFactory withSession(ClientSessionOptions options) {
default MongoDatabaseFactory withSession(ClientSessionOptions options) {
return withSession(getSession(options));
}
/**
* Obtain a {@link ClientSession} bound instance of {@link MongoDbFactory} returning {@link MongoDatabase} instances
* that are aware and bound to the given session.
* Obtain a {@link ClientSession} bound instance of {@link MongoDatabaseFactory} returning {@link MongoDatabase}
* instances that are aware and bound to the given session.
*
* @param session must not be {@literal null}.
* @return never {@literal null}.
* @since 2.1
*/
MongoDbFactory withSession(ClientSession session);
MongoDatabaseFactory withSession(ClientSession session);
/**
* Returns if the given {@link MongoDbFactory} is bound to a {@link ClientSession} that has an
* Returns if the given {@link MongoDatabaseFactory} is bound to a {@link ClientSession} that has an
* {@link ClientSession#hasActiveTransaction() active transaction}.
*
* @return {@literal true} if there's an active transaction, {@literal false} otherwise.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018-2019 the original author or authors.
* Copyright 2018-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,10 +27,10 @@ import com.mongodb.client.ClientSession;
import com.mongodb.client.MongoDatabase;
/**
* Helper class for managing a {@link MongoDatabase} instances via {@link MongoDbFactory}. Used for obtaining
* Helper class for managing a {@link MongoDatabase} instances via {@link MongoDatabaseFactory}. Used for obtaining
* {@link ClientSession session bound} resources, such as {@link MongoDatabase} and
* {@link com.mongodb.client.MongoCollection} suitable for transactional usage.
* <p />
* <br />
* <strong>Note:</strong> Intended for internal usage only.
*
* @author Christoph Strobl
@@ -41,93 +41,95 @@ import com.mongodb.client.MongoDatabase;
public class MongoDatabaseUtils {
/**
* Obtain the default {@link MongoDatabase database} form the given {@link MongoDbFactory factory} using
* Obtain the default {@link MongoDatabase database} form the given {@link MongoDatabaseFactory factory} using
* {@link SessionSynchronization#ON_ACTUAL_TRANSACTION native session synchronization}.
* <p />
* <br />
* Registers a {@link MongoSessionSynchronization MongoDB specific transaction synchronization} within the current
* {@link Thread} if {@link TransactionSynchronizationManager#isSynchronizationActive() synchronization is active}.
*
* @param factory the {@link MongoDbFactory} to get the {@link MongoDatabase} from.
* @param factory the {@link MongoDatabaseFactory} to get the {@link MongoDatabase} from.
* @return the {@link MongoDatabase} that is potentially associated with a transactional {@link ClientSession}.
*/
public static MongoDatabase getDatabase(MongoDbFactory factory) {
public static MongoDatabase getDatabase(MongoDatabaseFactory factory) {
return doGetMongoDatabase(null, factory, SessionSynchronization.ON_ACTUAL_TRANSACTION);
}
/**
* Obtain the default {@link MongoDatabase database} form the given {@link MongoDbFactory factory}.
* <p />
* Obtain the default {@link MongoDatabase database} form the given {@link MongoDatabaseFactory factory}.
* <br />
* Registers a {@link MongoSessionSynchronization MongoDB specific transaction synchronization} within the current
* {@link Thread} if {@link TransactionSynchronizationManager#isSynchronizationActive() synchronization is active}.
*
* @param factory the {@link MongoDbFactory} to get the {@link MongoDatabase} from.
* @param factory the {@link MongoDatabaseFactory} to get the {@link MongoDatabase} from.
* @param sessionSynchronization the synchronization to use. Must not be {@literal null}.
* @return the {@link MongoDatabase} that is potentially associated with a transactional {@link ClientSession}.
*/
public static MongoDatabase getDatabase(MongoDbFactory factory, SessionSynchronization sessionSynchronization) {
public static MongoDatabase getDatabase(MongoDatabaseFactory factory, SessionSynchronization sessionSynchronization) {
return doGetMongoDatabase(null, factory, sessionSynchronization);
}
/**
* Obtain the {@link MongoDatabase database} with given name form the given {@link MongoDbFactory factory} using
* Obtain the {@link MongoDatabase database} with given name form the given {@link MongoDatabaseFactory factory} using
* {@link SessionSynchronization#ON_ACTUAL_TRANSACTION native session synchronization}.
* <p />
* <br />
* Registers a {@link MongoSessionSynchronization MongoDB specific transaction synchronization} within the current
* {@link Thread} if {@link TransactionSynchronizationManager#isSynchronizationActive() synchronization is active}.
*
* @param dbName the name of the {@link MongoDatabase} to get.
* @param factory the {@link MongoDbFactory} to get the {@link MongoDatabase} from.
* @param factory the {@link MongoDatabaseFactory} to get the {@link MongoDatabase} from.
* @return the {@link MongoDatabase} that is potentially associated with a transactional {@link ClientSession}.
*/
public static MongoDatabase getDatabase(String dbName, MongoDbFactory factory) {
public static MongoDatabase getDatabase(@Nullable String dbName, MongoDatabaseFactory factory) {
return doGetMongoDatabase(dbName, factory, SessionSynchronization.ON_ACTUAL_TRANSACTION);
}
/**
* Obtain the {@link MongoDatabase database} with given name form the given {@link MongoDbFactory factory}.
* <p />
* Obtain the {@link MongoDatabase database} with given name form the given {@link MongoDatabaseFactory factory}.
* <br />
* Registers a {@link MongoSessionSynchronization MongoDB specific transaction synchronization} within the current
* {@link Thread} if {@link TransactionSynchronizationManager#isSynchronizationActive() synchronization is active}.
*
*
* @param dbName the name of the {@link MongoDatabase} to get.
* @param factory the {@link MongoDbFactory} to get the {@link MongoDatabase} from.
* @param factory the {@link MongoDatabaseFactory} to get the {@link MongoDatabase} from.
* @param sessionSynchronization the synchronization to use. Must not be {@literal null}.
* @return the {@link MongoDatabase} that is potentially associated with a transactional {@link ClientSession}.
*/
public static MongoDatabase getDatabase(String dbName, MongoDbFactory factory,
public static MongoDatabase getDatabase(@Nullable String dbName, MongoDatabaseFactory factory,
SessionSynchronization sessionSynchronization) {
return doGetMongoDatabase(dbName, factory, sessionSynchronization);
}
private static MongoDatabase doGetMongoDatabase(@Nullable String dbName, MongoDbFactory factory,
private static MongoDatabase doGetMongoDatabase(@Nullable String dbName, MongoDatabaseFactory factory,
SessionSynchronization sessionSynchronization) {
Assert.notNull(factory, "Factory must not be null!");
Assert.notNull(factory, "Factory must not be null");
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
return StringUtils.hasText(dbName) ? factory.getDb(dbName) : factory.getDb();
if (sessionSynchronization == SessionSynchronization.NEVER
|| !TransactionSynchronizationManager.isSynchronizationActive()) {
return StringUtils.hasText(dbName) ? factory.getMongoDatabase(dbName) : factory.getMongoDatabase();
}
ClientSession session = doGetSession(factory, sessionSynchronization);
if (session == null) {
return StringUtils.hasText(dbName) ? factory.getDb(dbName) : factory.getDb();
return StringUtils.hasText(dbName) ? factory.getMongoDatabase(dbName) : factory.getMongoDatabase();
}
MongoDbFactory factoryToUse = factory.withSession(session);
return StringUtils.hasText(dbName) ? factoryToUse.getDb(dbName) : factoryToUse.getDb();
MongoDatabaseFactory factoryToUse = factory.withSession(session);
return StringUtils.hasText(dbName) ? factoryToUse.getMongoDatabase(dbName) : factoryToUse.getMongoDatabase();
}
/**
* Check if the {@link MongoDbFactory} is actually bound to a {@link ClientSession} that has an active transaction, or
* if a {@link TransactionSynchronization} has been registered for the {@link MongoDbFactory resource} and if the
* associated {@link ClientSession} has an {@link ClientSession#hasActiveTransaction() active transaction}.
* Check if the {@link MongoDatabaseFactory} is actually bound to a {@link ClientSession} that has an active
* transaction, or if a {@link TransactionSynchronization} has been registered for the {@link MongoDatabaseFactory
* resource} and if the associated {@link ClientSession} has an {@link ClientSession#hasActiveTransaction() active
* transaction}.
*
* @param dbFactory the resource to check transactions for. Must not be {@literal null}.
* @return {@literal true} if the factory has an ongoing transaction.
* @since 2.1.3
*/
public static boolean isTransactionActive(MongoDbFactory dbFactory) {
public static boolean isTransactionActive(MongoDatabaseFactory dbFactory) {
if (dbFactory.isTransactionActive()) {
return true;
@@ -138,7 +140,8 @@ public class MongoDatabaseUtils {
}
@Nullable
private static ClientSession doGetSession(MongoDbFactory dbFactory, SessionSynchronization sessionSynchronization) {
private static ClientSession doGetSession(MongoDatabaseFactory dbFactory,
SessionSynchronization sessionSynchronization) {
MongoResourceHolder resourceHolder = (MongoResourceHolder) TransactionSynchronizationManager.getResource(dbFactory);
@@ -169,7 +172,7 @@ public class MongoDatabaseUtils {
return resourceHolder.getSession();
}
private static ClientSession createClientSession(MongoDbFactory dbFactory) {
private static ClientSession createClientSession(MongoDatabaseFactory dbFactory) {
return dbFactory.getSession(ClientSessionOptions.builder().causallyConsistent(true).build());
}
@@ -184,25 +187,17 @@ public class MongoDatabaseUtils {
private final MongoResourceHolder resourceHolder;
MongoSessionSynchronization(MongoResourceHolder resourceHolder, MongoDbFactory dbFactory) {
MongoSessionSynchronization(MongoResourceHolder resourceHolder, MongoDatabaseFactory dbFactory) {
super(resourceHolder, dbFactory);
this.resourceHolder = resourceHolder;
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.support.ResourceHolderSynchronization#shouldReleaseBeforeCompletion()
*/
@Override
protected boolean shouldReleaseBeforeCompletion() {
return false;
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.support.ResourceHolderSynchronization#processResourceAfterCommit(java.lang.Object)
*/
@Override
protected void processResourceAfterCommit(MongoResourceHolder resourceHolder) {
@@ -211,10 +206,6 @@ public class MongoDatabaseUtils {
}
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.support.ResourceHolderSynchronization#afterCompletion(int)
*/
@Override
public void afterCompletion(int status) {
@@ -225,10 +216,6 @@ public class MongoDatabaseUtils {
super.afterCompletion(status);
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.support.ResourceHolderSynchronization#releaseResource(java.lang.Object, java.lang.Object)
*/
@Override
protected void releaseResource(MongoResourceHolder resourceHolder, Object resourceKey) {

View File

@@ -0,0 +1,73 @@
/*
* Copyright 2021-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb;
/**
* Wrapper object for MongoDB expressions like {@code $toUpper : $name} that manifest as {@link org.bson.Document} when
* passed on to the driver.
* <br />
* A set of predefined {@link MongoExpression expressions}, including a
* {@link org.springframework.data.mongodb.core.aggregation.AggregationSpELExpression SpEL based variant} for method
* like expressions (eg. {@code toUpper(name)}) are available via the
* {@link org.springframework.data.mongodb.core.aggregation Aggregation API}.
*
* @author Christoph Strobl
* @since 3.2
* @see org.springframework.data.mongodb.core.aggregation.ArithmeticOperators
* @see org.springframework.data.mongodb.core.aggregation.ArrayOperators
* @see org.springframework.data.mongodb.core.aggregation.ComparisonOperators
* @see org.springframework.data.mongodb.core.aggregation.ConditionalOperators
* @see org.springframework.data.mongodb.core.aggregation.ConvertOperators
* @see org.springframework.data.mongodb.core.aggregation.DateOperators
* @see org.springframework.data.mongodb.core.aggregation.ObjectOperators
* @see org.springframework.data.mongodb.core.aggregation.SetOperators
* @see org.springframework.data.mongodb.core.aggregation.StringOperators
*/
@FunctionalInterface
public interface MongoExpression {
/**
* Create a new {@link MongoExpression} from plain {@link String} (eg. {@code $toUpper : $name}). <br />
* The given expression will be wrapped with <code>{ ... }</code> to match an actual MongoDB {@link org.bson.Document}
* if necessary.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link MongoExpression}.
*/
static MongoExpression create(String expression) {
return new BindableMongoExpression(expression, null);
}
/**
* Create a new {@link MongoExpression} from plain {@link String} containing placeholders (eg. {@code $toUpper : ?0})
* that will be resolved on first call of {@link #toDocument()}. <br />
* The given expression will be wrapped with <code>{ ... }</code> to match an actual MongoDB {@link org.bson.Document}
* if necessary.
*
* @param expression must not be {@literal null}.
* @return new instance of {@link MongoExpression}.
*/
static MongoExpression create(String expression, Object... args) {
return new BindableMongoExpression(expression, args);
}
/**
* Obtain the native {@link org.bson.Document} representation.
*
* @return never {@literal null}.
*/
org.bson.Document toDocument();
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright 2022-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb;
import java.util.Arrays;
import java.util.function.Consumer;
import org.springframework.data.domain.ManagedTypes;
/**
* @author Christoph Strobl
* @since 4.0
*/
public final class MongoManagedTypes implements ManagedTypes {
private final ManagedTypes delegate;
private MongoManagedTypes(ManagedTypes types) {
this.delegate = types;
}
/**
* Wraps an existing {@link ManagedTypes} object with {@link MongoManagedTypes}.
*
* @param managedTypes
* @return
*/
public static MongoManagedTypes from(ManagedTypes managedTypes) {
return new MongoManagedTypes(managedTypes);
}
/**
* Factory method used to construct {@link MongoManagedTypes} from the given array of {@link Class types}.
*
* @param types array of {@link Class types} used to initialize the {@link ManagedTypes}; must not be {@literal null}.
* @return new instance of {@link MongoManagedTypes} initialized from {@link Class types}.
*/
public static MongoManagedTypes from(Class<?>... types) {
return fromIterable(Arrays.asList(types));
}
/**
* Factory method used to construct {@link MongoManagedTypes} from the given, required {@link Iterable} of
* {@link Class types}.
*
* @param types {@link Iterable} of {@link Class types} used to initialize the {@link ManagedTypes}; must not be
* {@literal null}.
* @return new instance of {@link MongoManagedTypes} initialized the given, required {@link Iterable} of {@link Class
* types}.
*/
public static MongoManagedTypes fromIterable(Iterable<? extends Class<?>> types) {
return from(ManagedTypes.fromIterable(types));
}
/**
* Factory method to return an empty {@link MongoManagedTypes} object.
*
* @return an empty {@link MongoManagedTypes} object.
*/
public static MongoManagedTypes empty() {
return from(ManagedTypes.empty());
}
@Override
public void forEach(Consumer<Class<?>> action) {
delegate.forEach(action);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018-2019 the original author or authors.
* Copyright 2018-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,7 +24,7 @@ import com.mongodb.client.ClientSession;
/**
* MongoDB specific {@link ResourceHolderSupport resource holder}, wrapping a {@link ClientSession}.
* {@link MongoTransactionManager} binds instances of this class to the thread.
* <p />
* <br />
* <strong>Note:</strong> Intended for internal usage only.
*
* @author Christoph Strobl
@@ -36,15 +36,15 @@ import com.mongodb.client.ClientSession;
class MongoResourceHolder extends ResourceHolderSupport {
private @Nullable ClientSession session;
private MongoDbFactory dbFactory;
private MongoDatabaseFactory dbFactory;
/**
* Create a new {@link MongoResourceHolder} for a given {@link ClientSession session}.
*
* @param session the associated {@link ClientSession}. Can be {@literal null}.
* @param dbFactory the associated {@link MongoDbFactory}. must not be {@literal null}.
* @param dbFactory the associated {@link MongoDatabaseFactory}. must not be {@literal null}.
*/
MongoResourceHolder(@Nullable ClientSession session, MongoDbFactory dbFactory) {
MongoResourceHolder(@Nullable ClientSession session, MongoDatabaseFactory dbFactory) {
this.session = session;
this.dbFactory = dbFactory;
@@ -68,16 +68,16 @@ class MongoResourceHolder extends ResourceHolderSupport {
ClientSession session = getSession();
if (session == null) {
throw new IllegalStateException("No session available!");
throw new IllegalStateException("No session available");
}
return session;
}
/**
* @return the associated {@link MongoDbFactory}.
* @return the associated {@link MongoDatabaseFactory}.
*/
public MongoDbFactory getDbFactory() {
public MongoDatabaseFactory getDbFactory() {
return dbFactory;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018-2019 the original author or authors.
* Copyright 2018-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018-2019 the original author or authors.
* Copyright 2018-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018-2019 the original author or authors.
* Copyright 2018-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,18 +36,19 @@ import com.mongodb.client.ClientSession;
/**
* A {@link org.springframework.transaction.PlatformTransactionManager} implementation that manages
* {@link ClientSession} based transactions for a single {@link MongoDbFactory}.
* <p />
* Binds a {@link ClientSession} from the specified {@link MongoDbFactory} to the thread.
* <p />
* {@link ClientSession} based transactions for a single {@link MongoDatabaseFactory}.
* <br />
* Binds a {@link ClientSession} from the specified {@link MongoDatabaseFactory} to the thread.
* <br />
* {@link TransactionDefinition#isReadOnly() Readonly} transactions operate on a {@link ClientSession} and enable causal
* consistency, and also {@link ClientSession#startTransaction() start}, {@link ClientSession#commitTransaction()
* commit} or {@link ClientSession#abortTransaction() abort} a transaction.
* <p />
* <br />
* Application code is required to retrieve the {@link com.mongodb.client.MongoDatabase} via
* {@link MongoDatabaseUtils#getDatabase(MongoDbFactory)} instead of a standard {@link MongoDbFactory#getDb()} call.
* Spring classes such as {@link org.springframework.data.mongodb.core.MongoTemplate} use this strategy implicitly.
* <p />
* {@link MongoDatabaseUtils#getDatabase(MongoDatabaseFactory)} instead of a standard
* {@link MongoDatabaseFactory#getMongoDatabase()} call. Spring classes such as
* {@link org.springframework.data.mongodb.core.MongoTemplate} use this strategy implicitly.
* <br />
* By default failure of a {@literal commit} operation raises a {@link TransactionSystemException}. One may override
* {@link #doCommit(MongoTransactionObject)} to implement the
* <a href="https://docs.mongodb.com/manual/core/transactions/#retry-commit-operation">Retry Commit Operation</a>
@@ -58,57 +59,53 @@ import com.mongodb.client.ClientSession;
* @currentRead Shadow's Edge - Brent Weeks
* @since 2.1
* @see <a href="https://www.mongodb.com/transactions">MongoDB Transaction Documentation</a>
* @see MongoDatabaseUtils#getDatabase(MongoDbFactory, SessionSynchronization)
* @see MongoDatabaseUtils#getDatabase(MongoDatabaseFactory, SessionSynchronization)
*/
public class MongoTransactionManager extends AbstractPlatformTransactionManager
implements ResourceTransactionManager, InitializingBean {
private @Nullable MongoDbFactory dbFactory;
private @Nullable MongoDatabaseFactory dbFactory;
private @Nullable TransactionOptions options;
/**
* Create a new {@link MongoTransactionManager} for bean-style usage.
* <p />
* <strong>Note:</strong>The {@link MongoDbFactory db factory} has to be {@link #setDbFactory(MongoDbFactory) set}
* before using the instance. Use this constructor to prepare a {@link MongoTransactionManager} via a
* {@link org.springframework.beans.factory.BeanFactory}.
* <p />
* <br />
* <strong>Note:</strong>The {@link MongoDatabaseFactory db factory} has to be
* {@link #setDbFactory(MongoDatabaseFactory) set} before using the instance. Use this constructor to prepare a
* {@link MongoTransactionManager} via a {@link org.springframework.beans.factory.BeanFactory}.
* <br />
* Optionally it is possible to set default {@link TransactionOptions transaction options} defining
* {@link com.mongodb.ReadConcern} and {@link com.mongodb.WriteConcern}.
*
* @see #setDbFactory(MongoDbFactory)
* @see #setDbFactory(MongoDatabaseFactory)
* @see #setTransactionSynchronization(int)
*/
public MongoTransactionManager() {}
/**
* Create a new {@link MongoTransactionManager} obtaining sessions from the given {@link MongoDbFactory}.
* Create a new {@link MongoTransactionManager} obtaining sessions from the given {@link MongoDatabaseFactory}.
*
* @param dbFactory must not be {@literal null}.
*/
public MongoTransactionManager(MongoDbFactory dbFactory) {
public MongoTransactionManager(MongoDatabaseFactory dbFactory) {
this(dbFactory, null);
}
/**
* Create a new {@link MongoTransactionManager} obtaining sessions from the given {@link MongoDbFactory} applying the
* given {@link TransactionOptions options}, if present, when starting a new transaction.
* Create a new {@link MongoTransactionManager} obtaining sessions from the given {@link MongoDatabaseFactory}
* applying the given {@link TransactionOptions options}, if present, when starting a new transaction.
*
* @param dbFactory must not be {@literal null}.
* @param options can be {@literal null}.
*/
public MongoTransactionManager(MongoDbFactory dbFactory, @Nullable TransactionOptions options) {
public MongoTransactionManager(MongoDatabaseFactory dbFactory, @Nullable TransactionOptions options) {
Assert.notNull(dbFactory, "DbFactory must not be null!");
Assert.notNull(dbFactory, "DbFactory must not be null");
this.dbFactory = dbFactory;
this.options = options;
}
/*
* (non-Javadoc)
* org.springframework.transaction.support.AbstractPlatformTransactionManager#doGetTransaction()
*/
@Override
protected Object doGetTransaction() throws TransactionException {
@@ -117,19 +114,11 @@ public class MongoTransactionManager extends AbstractPlatformTransactionManager
return new MongoTransactionObject(resourceHolder);
}
/*
* (non-Javadoc)
* org.springframework.transaction.support.AbstractPlatformTransactionManager#isExistingTransaction(java.lang.Object)
*/
@Override
protected boolean isExistingTransaction(Object transaction) throws TransactionException {
return extractMongoTransaction(transaction).hasResourceHolder();
}
/*
* (non-Javadoc)
* org.springframework.transaction.support.AbstractPlatformTransactionManager#doBegin(java.lang.Object, org.springframework.transaction.TransactionDefinition)
*/
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException {
@@ -159,10 +148,6 @@ public class MongoTransactionManager extends AbstractPlatformTransactionManager
TransactionSynchronizationManager.bindResource(getRequiredDbFactory(), resourceHolder);
}
/*
* (non-Javadoc)
* org.springframework.transaction.support.AbstractPlatformTransactionManager#doSuspend(java.lang.Object)
*/
@Override
protected Object doSuspend(Object transaction) throws TransactionException {
@@ -172,19 +157,11 @@ public class MongoTransactionManager extends AbstractPlatformTransactionManager
return TransactionSynchronizationManager.unbindResource(getRequiredDbFactory());
}
/*
* (non-Javadoc)
* org.springframework.transaction.support.AbstractPlatformTransactionManager#doResume(java.lang.Object, java.lang.Object)
*/
@Override
protected void doResume(@Nullable Object transaction, Object suspendedResources) {
TransactionSynchronizationManager.bindResource(getRequiredDbFactory(), suspendedResources);
}
/*
* (non-Javadoc)
* org.springframework.transaction.support.AbstractPlatformTransactionManager#doCommit(org.springframework.transaction.support.DefaultTransactionStatus)
*/
@Override
protected final void doCommit(DefaultTransactionStatus status) throws TransactionException {
@@ -211,8 +188,8 @@ public class MongoTransactionManager extends AbstractPlatformTransactionManager
* By default those labels are ignored, nevertheless one might check for
* {@link MongoException#UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL transient commit errors labels} and retry the the
* commit. <br />
* <pre>
* <code>
* <pre>
* int retries = 3;
* do {
* try {
@@ -225,8 +202,8 @@ public class MongoTransactionManager extends AbstractPlatformTransactionManager
* }
* Thread.sleep(500);
* } while (--retries > 0);
* </pre>
* </code>
* </pre>
*
* @param transactionObject never {@literal null}.
* @throws Exception in case of transaction errors.
@@ -235,10 +212,6 @@ public class MongoTransactionManager extends AbstractPlatformTransactionManager
transactionObject.commitTransaction();
}
/*
* (non-Javadoc)
* org.springframework.transaction.support.AbstractPlatformTransactionManager#doRollback(org.springframework.transaction.support.DefaultTransactionStatus)
*/
@Override
protected void doRollback(DefaultTransactionStatus status) throws TransactionException {
@@ -258,10 +231,6 @@ public class MongoTransactionManager extends AbstractPlatformTransactionManager
}
}
/*
* (non-Javadoc)
* org.springframework.transaction.support.AbstractPlatformTransactionManager#doSetRollbackOnly(org.springframework.transaction.support.DefaultTransactionStatus)
*/
@Override
protected void doSetRollbackOnly(DefaultTransactionStatus status) throws TransactionException {
@@ -269,10 +238,6 @@ public class MongoTransactionManager extends AbstractPlatformTransactionManager
transactionObject.getRequiredResourceHolder().setRollbackOnly();
}
/*
* (non-Javadoc)
* org.springframework.transaction.support.AbstractPlatformTransactionManager#doCleanupAfterCompletion(java.lang.Object)
*/
@Override
protected void doCleanupAfterCompletion(Object transaction) {
@@ -295,13 +260,13 @@ public class MongoTransactionManager extends AbstractPlatformTransactionManager
}
/**
* Set the {@link MongoDbFactory} that this instance should manage transactions for.
* Set the {@link MongoDatabaseFactory} that this instance should manage transactions for.
*
* @param dbFactory must not be {@literal null}.
*/
public void setDbFactory(MongoDbFactory dbFactory) {
public void setDbFactory(MongoDatabaseFactory dbFactory) {
Assert.notNull(dbFactory, "DbFactory must not be null!");
Assert.notNull(dbFactory, "DbFactory must not be null");
this.dbFactory = dbFactory;
}
@@ -315,28 +280,20 @@ public class MongoTransactionManager extends AbstractPlatformTransactionManager
}
/**
* Get the {@link MongoDbFactory} that this instance manages transactions for.
* Get the {@link MongoDatabaseFactory} that this instance manages transactions for.
*
* @return can be {@literal null}.
*/
@Nullable
public MongoDbFactory getDbFactory() {
public MongoDatabaseFactory getDbFactory() {
return dbFactory;
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.support.ResourceTransactionManager#getResourceFactory()
*/
@Override
public MongoDbFactory getResourceFactory() {
public MongoDatabaseFactory getResourceFactory() {
return getRequiredDbFactory();
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() {
getRequiredDbFactory();
@@ -344,7 +301,7 @@ public class MongoTransactionManager extends AbstractPlatformTransactionManager
private MongoResourceHolder newResourceHolder(TransactionDefinition definition, ClientSessionOptions options) {
MongoDbFactory dbFactory = getResourceFactory();
MongoDatabaseFactory dbFactory = getResourceFactory();
MongoResourceHolder resourceHolder = new MongoResourceHolder(dbFactory.getSession(options), dbFactory);
resourceHolder.setTimeoutIfNotDefaulted(determineTimeout(definition));
@@ -355,10 +312,10 @@ public class MongoTransactionManager extends AbstractPlatformTransactionManager
/**
* @throws IllegalStateException if {@link #dbFactory} is {@literal null}.
*/
private MongoDbFactory getRequiredDbFactory() {
private MongoDatabaseFactory getRequiredDbFactory() {
Assert.state(dbFactory != null,
"MongoTransactionManager operates upon a MongoDbFactory. Did you forget to provide one? It's required.");
"MongoTransactionManager operates upon a MongoDbFactory; Did you forget to provide one; It's required");
return dbFactory;
}
@@ -396,7 +353,7 @@ public class MongoTransactionManager extends AbstractPlatformTransactionManager
debugString += String.format("causallyConsistent = %s, ", session.isCausallyConsistent());
debugString += String.format("txActive = %s, ", session.hasActiveTransaction());
debugString += String.format("txNumber = %d, ", session.getServerSession().getTransactionNumber());
debugString += String.format("closed = %d, ", session.getServerSession().isClosed());
debugString += String.format("closed = %b, ", session.getServerSession().isClosed());
debugString += String.format("clusterTime = %s", session.getClusterTime());
} else {
debugString += "id = n/a";
@@ -493,30 +450,22 @@ public class MongoTransactionManager extends AbstractPlatformTransactionManager
private MongoResourceHolder getRequiredResourceHolder() {
Assert.state(resourceHolder != null, "MongoResourceHolder is required but not present. o_O");
Assert.state(resourceHolder != null, "MongoResourceHolder is required but not present; o_O");
return resourceHolder;
}
private ClientSession getRequiredSession() {
ClientSession session = getSession();
Assert.state(session != null, "A Session is required but it turned out to be null.");
Assert.state(session != null, "A Session is required but it turned out to be null");
return session;
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.support.SmartTransactionObject#isRollbackOnly()
*/
@Override
public boolean isRollbackOnly() {
return this.resourceHolder != null && this.resourceHolder.isRollbackOnly();
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.support.SmartTransactionObject#flush()
*/
@Override
public void flush() {
TransactionSynchronizationUtils.triggerFlush();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016-2019 the original author or authors.
* Copyright 2016-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,6 +31,7 @@ import com.mongodb.reactivestreams.client.MongoDatabase;
*
* @author Mark Paluch
* @author Christoph Strobl
* @author Mathieu Ouellet
* @since 2.0
*/
public interface ReactiveMongoDatabaseFactory extends CodecRegistryProvider {
@@ -38,19 +39,19 @@ public interface ReactiveMongoDatabaseFactory extends CodecRegistryProvider {
/**
* Creates a default {@link MongoDatabase} instance.
*
* @return
* @return never {@literal null}.
* @throws DataAccessException
*/
MongoDatabase getMongoDatabase() throws DataAccessException;
Mono<MongoDatabase> getMongoDatabase() throws DataAccessException;
/**
* Creates a {@link MongoDatabase} instance to access the database with the given name.
* Obtain a {@link MongoDatabase} instance to access the database with the given name.
*
* @param dbName must not be {@literal null} or empty.
* @return
* @return never {@literal null}.
* @throws DataAccessException
*/
MongoDatabase getMongoDatabase(String dbName) throws DataAccessException;
Mono<MongoDatabase> getMongoDatabase(String dbName) throws DataAccessException;
/**
* Exposes a shared {@link MongoExceptionTranslator}.
@@ -64,10 +65,7 @@ public interface ReactiveMongoDatabaseFactory extends CodecRegistryProvider {
*
* @return never {@literal null}.
*/
@Override
default CodecRegistry getCodecRegistry() {
return getMongoDatabase().getCodecRegistry();
}
CodecRegistry getCodecRegistry();
/**
* Obtain a {@link Mono} emitting a {@link ClientSession} for given {@link ClientSessionOptions options}.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2019 the original author or authors.
* Copyright 2019-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,11 +36,12 @@ import com.mongodb.reactivestreams.client.MongoDatabase;
* Helper class for managing reactive {@link MongoDatabase} instances via {@link ReactiveMongoDatabaseFactory}. Used for
* obtaining {@link ClientSession session bound} resources, such as {@link MongoDatabase} and {@link MongoCollection}
* suitable for transactional usage.
* <p />
* <br />
* <strong>Note:</strong> Intended for internal usage only.
*
* @author Mark Paluch
* @author Christoph Strobl
* @author Mathieu Ouellet
* @since 2.2
*/
public class ReactiveMongoDatabaseUtils {
@@ -74,7 +75,7 @@ public class ReactiveMongoDatabaseUtils {
/**
* Obtain the default {@link MongoDatabase database} form the given {@link ReactiveMongoDatabaseFactory factory} using
* {@link SessionSynchronization#ON_ACTUAL_TRANSACTION native session synchronization}.
* <p />
* <br />
* Registers a {@link MongoSessionSynchronization MongoDB specific transaction synchronization} within the subscriber
* {@link Context} if {@link TransactionSynchronizationManager#isSynchronizationActive() synchronization is active}.
*
@@ -87,7 +88,7 @@ public class ReactiveMongoDatabaseUtils {
/**
* Obtain the default {@link MongoDatabase database} form the given {@link ReactiveMongoDatabaseFactory factory}.
* <p />
* <br />
* Registers a {@link MongoSessionSynchronization MongoDB specific transaction synchronization} within the subscriber
* {@link Context} if {@link TransactionSynchronizationManager#isSynchronizationActive() synchronization is active}.
*
@@ -103,7 +104,7 @@ public class ReactiveMongoDatabaseUtils {
/**
* Obtain the {@link MongoDatabase database} with given name form the given {@link ReactiveMongoDatabaseFactory
* factory} using {@link SessionSynchronization#ON_ACTUAL_TRANSACTION native session synchronization}.
* <p />
* <br />
* Registers a {@link MongoSessionSynchronization MongoDB specific transaction synchronization} within the subscriber
* {@link Context} if {@link TransactionSynchronizationManager#isSynchronizationActive() synchronization is active}.
*
@@ -118,7 +119,7 @@ public class ReactiveMongoDatabaseUtils {
/**
* Obtain the {@link MongoDatabase database} with given name form the given {@link ReactiveMongoDatabaseFactory
* factory}.
* <p />
* <br />
* Registers a {@link MongoSessionSynchronization MongoDB specific transaction synchronization} within the subscriber
* {@link Context} if {@link TransactionSynchronizationManager#isSynchronizationActive() synchronization is active}.
*
@@ -135,21 +136,24 @@ public class ReactiveMongoDatabaseUtils {
private static Mono<MongoDatabase> doGetMongoDatabase(@Nullable String dbName, ReactiveMongoDatabaseFactory factory,
SessionSynchronization sessionSynchronization) {
Assert.notNull(factory, "DatabaseFactory must not be null!");
Assert.notNull(factory, "DatabaseFactory must not be null");
if (sessionSynchronization == SessionSynchronization.NEVER) {
return getMongoDatabaseOrDefault(dbName, factory);
}
return TransactionSynchronizationManager.forCurrentTransaction()
.filter(TransactionSynchronizationManager::isSynchronizationActive) //
.flatMap(synchronizationManager -> {
return doGetSession(synchronizationManager, factory, sessionSynchronization) //
.map(it -> getMongoDatabaseOrDefault(dbName, factory.withSession(it)));
})
.onErrorResume(NoTransactionException.class,
e -> Mono.fromSupplier(() -> getMongoDatabaseOrDefault(dbName, factory)))
.defaultIfEmpty(getMongoDatabaseOrDefault(dbName, factory));
.flatMap(it -> getMongoDatabaseOrDefault(dbName, factory.withSession(it)));
}) //
.onErrorResume(NoTransactionException.class, e -> getMongoDatabaseOrDefault(dbName, factory))
.switchIfEmpty(getMongoDatabaseOrDefault(dbName, factory));
}
private static MongoDatabase getMongoDatabaseOrDefault(@Nullable String dbName,
private static Mono<MongoDatabase> getMongoDatabaseOrDefault(@Nullable String dbName,
ReactiveMongoDatabaseFactory factory) {
return StringUtils.hasText(dbName) ? factory.getMongoDatabase(dbName) : factory.getMongoDatabase();
}
@@ -210,19 +214,11 @@ public class ReactiveMongoDatabaseUtils {
this.resourceHolder = resourceHolder;
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.reactive.ReactiveResourceSynchronization#shouldReleaseBeforeCompletion()
*/
@Override
protected boolean shouldReleaseBeforeCompletion() {
return false;
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.reactive.ReactiveResourceSynchronization#processResourceAfterCommit(java.lang.Object)
*/
@Override
protected Mono<Void> processResourceAfterCommit(ReactiveMongoResourceHolder resourceHolder) {
@@ -233,10 +229,6 @@ public class ReactiveMongoDatabaseUtils {
return Mono.empty();
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.reactive.ReactiveResourceSynchronization#afterCompletion(int)
*/
@Override
public Mono<Void> afterCompletion(int status) {
@@ -252,10 +244,6 @@ public class ReactiveMongoDatabaseUtils {
});
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.reactive.ReactiveResourceSynchronization#releaseResource(java.lang.Object, java.lang.Object)
*/
@Override
protected Mono<Void> releaseResource(ReactiveMongoResourceHolder resourceHolder, Object resourceKey) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2019 the original author or authors.
* Copyright 2019-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,7 +24,7 @@ import com.mongodb.reactivestreams.client.ClientSession;
/**
* MongoDB specific resource holder, wrapping a {@link ClientSession}. {@link ReactiveMongoTransactionManager} binds
* instances of this class to the subscriber context.
* <p />
* <br />
* <strong>Note:</strong> Intended for internal usage only.
*
* @author Mark Paluch
@@ -42,7 +42,7 @@ class ReactiveMongoResourceHolder extends ResourceHolderSupport {
* Create a new {@link ReactiveMongoResourceHolder} for a given {@link ClientSession session}.
*
* @param session the associated {@link ClientSession}. Can be {@literal null}.
* @param databaseFactory the associated {@link MongoDbFactory}. must not be {@literal null}.
* @param databaseFactory the associated {@link MongoDatabaseFactory}. must not be {@literal null}.
*/
ReactiveMongoResourceHolder(@Nullable ClientSession session, ReactiveMongoDatabaseFactory databaseFactory) {
@@ -99,7 +99,7 @@ class ReactiveMongoResourceHolder extends ResourceHolderSupport {
* If the {@link ReactiveMongoResourceHolder} is {@link #hasSession() not already associated} with a
* {@link ClientSession} the given value is {@link #setSession(ClientSession) set} and returned, otherwise the current
* bound session is returned.
*
*
* @param session
* @return
*/

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2019 the original author or authors.
* Copyright 2019-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,21 +38,21 @@ import com.mongodb.reactivestreams.client.ClientSession;
* A {@link org.springframework.transaction.ReactiveTransactionManager} implementation that manages
* {@link com.mongodb.reactivestreams.client.ClientSession} based transactions for a single
* {@link org.springframework.data.mongodb.ReactiveMongoDatabaseFactory}.
* <p />
* <br />
* Binds a {@link ClientSession} from the specified
* {@link org.springframework.data.mongodb.ReactiveMongoDatabaseFactory} to the subscriber
* {@link reactor.util.context.Context}.
* <p />
* <br />
* {@link org.springframework.transaction.TransactionDefinition#isReadOnly() Readonly} transactions operate on a
* {@link ClientSession} and enable causal consistency, and also {@link ClientSession#startTransaction() start},
* {@link com.mongodb.reactivestreams.client.ClientSession#commitTransaction() commit} or
* {@link ClientSession#abortTransaction() abort} a transaction.
* <p />
* <br />
* Application code is required to retrieve the {@link com.mongodb.reactivestreams.client.MongoDatabase} via
* {@link org.springframework.data.mongodb.ReactiveMongoDatabaseUtils#getDatabase(ReactiveMongoDatabaseFactory)} instead
* of a standard {@link org.springframework.data.mongodb.ReactiveMongoDatabaseFactory#getMongoDatabase()} call. Spring
* classes such as {@link org.springframework.data.mongodb.core.ReactiveMongoTemplate} use this strategy implicitly.
* <p />
* <br />
* By default failure of a {@literal commit} operation raises a {@link TransactionSystemException}. You can override
* {@link #doCommit(TransactionSynchronizationManager, ReactiveMongoTransactionObject)} to implement the
* <a href="https://docs.mongodb.com/manual/core/transactions/#retry-commit-operation">Retry Commit Operation</a>
@@ -71,11 +71,11 @@ public class ReactiveMongoTransactionManager extends AbstractReactiveTransaction
/**
* Create a new {@link ReactiveMongoTransactionManager} for bean-style usage.
* <p />
* <br />
* <strong>Note:</strong>The {@link org.springframework.data.mongodb.ReactiveMongoDatabaseFactory db factory} has to
* be {@link #setDatabaseFactory(ReactiveMongoDatabaseFactory)} set} before using the instance. Use this constructor
* to prepare a {@link ReactiveMongoTransactionManager} via a {@link org.springframework.beans.factory.BeanFactory}.
* <p />
* <br />
* Optionally it is possible to set default {@link TransactionOptions transaction options} defining
* {@link com.mongodb.ReadConcern} and {@link com.mongodb.WriteConcern}.
*
@@ -104,16 +104,12 @@ public class ReactiveMongoTransactionManager extends AbstractReactiveTransaction
public ReactiveMongoTransactionManager(ReactiveMongoDatabaseFactory databaseFactory,
@Nullable TransactionOptions options) {
Assert.notNull(databaseFactory, "DatabaseFactory must not be null!");
Assert.notNull(databaseFactory, "DatabaseFactory must not be null");
this.databaseFactory = databaseFactory;
this.options = options;
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.reactive.AbstractReactiveTransactionManager#doGetTransaction(org.springframework.transaction.reactive.TransactionSynchronizationManager)
*/
@Override
protected Object doGetTransaction(TransactionSynchronizationManager synchronizationManager)
throws TransactionException {
@@ -123,19 +119,11 @@ public class ReactiveMongoTransactionManager extends AbstractReactiveTransaction
return new ReactiveMongoTransactionObject(resourceHolder);
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.reactive.AbstractReactiveTransactionManager#isExistingTransaction(java.lang.Object)
*/
@Override
protected boolean isExistingTransaction(Object transaction) throws TransactionException {
return extractMongoTransaction(transaction).hasResourceHolder();
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.reactive.AbstractReactiveTransactionManager#doBegin(org.springframework.transaction.reactive.TransactionSynchronizationManager, java.lang.Object, org.springframework.transaction.TransactionDefinition)
*/
@Override
protected Mono<Void> doBegin(TransactionSynchronizationManager synchronizationManager, Object transaction,
TransactionDefinition definition) throws TransactionException {
@@ -175,10 +163,6 @@ public class ReactiveMongoTransactionManager extends AbstractReactiveTransaction
});
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.reactive.AbstractReactiveTransactionManager#doSuspend(org.springframework.transaction.reactive.TransactionSynchronizationManager, java.lang.Object)
*/
@Override
protected Mono<Object> doSuspend(TransactionSynchronizationManager synchronizationManager, Object transaction)
throws TransactionException {
@@ -192,10 +176,6 @@ public class ReactiveMongoTransactionManager extends AbstractReactiveTransaction
});
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.reactive.AbstractReactiveTransactionManager#doResume(org.springframework.transaction.reactive.TransactionSynchronizationManager, java.lang.Object, java.lang.Object)
*/
@Override
protected Mono<Void> doResume(TransactionSynchronizationManager synchronizationManager, @Nullable Object transaction,
Object suspendedResources) {
@@ -203,10 +183,6 @@ public class ReactiveMongoTransactionManager extends AbstractReactiveTransaction
.fromRunnable(() -> synchronizationManager.bindResource(getRequiredDatabaseFactory(), suspendedResources));
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.reactive.AbstractReactiveTransactionManager#doCommit(org.springframework.transaction.reactive.TransactionSynchronizationManager, org.springframework.transaction.reactive.GenericReactiveTransaction)
*/
@Override
protected final Mono<Void> doCommit(TransactionSynchronizationManager synchronizationManager,
GenericReactiveTransaction status) throws TransactionException {
@@ -243,10 +219,6 @@ public class ReactiveMongoTransactionManager extends AbstractReactiveTransaction
return transactionObject.commitTransaction();
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.reactive.AbstractReactiveTransactionManager#doRollback(org.springframework.transaction.reactive.TransactionSynchronizationManager, org.springframework.transaction.reactive.GenericReactiveTransaction)
*/
@Override
protected Mono<Void> doRollback(TransactionSynchronizationManager synchronizationManager,
GenericReactiveTransaction status) {
@@ -268,10 +240,6 @@ public class ReactiveMongoTransactionManager extends AbstractReactiveTransaction
});
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.reactive.AbstractReactiveTransactionManager#doSetRollbackOnly(org.springframework.transaction.reactive.TransactionSynchronizationManager, org.springframework.transaction.reactive.GenericReactiveTransaction)
*/
@Override
protected Mono<Void> doSetRollbackOnly(TransactionSynchronizationManager synchronizationManager,
GenericReactiveTransaction status) throws TransactionException {
@@ -282,10 +250,6 @@ public class ReactiveMongoTransactionManager extends AbstractReactiveTransaction
});
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.reactive.AbstractReactiveTransactionManager#doCleanupAfterCompletion(org.springframework.transaction.reactive.TransactionSynchronizationManager, java.lang.Object)
*/
@Override
protected Mono<Void> doCleanupAfterCompletion(TransactionSynchronizationManager synchronizationManager,
Object transaction) {
@@ -317,7 +281,7 @@ public class ReactiveMongoTransactionManager extends AbstractReactiveTransaction
*/
public void setDatabaseFactory(ReactiveMongoDatabaseFactory databaseFactory) {
Assert.notNull(databaseFactory, "DatabaseFactory must not be null!");
Assert.notNull(databaseFactory, "DatabaseFactory must not be null");
this.databaseFactory = databaseFactory;
}
@@ -340,10 +304,6 @@ public class ReactiveMongoTransactionManager extends AbstractReactiveTransaction
return databaseFactory;
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() {
getRequiredDatabaseFactory();
@@ -363,7 +323,7 @@ public class ReactiveMongoTransactionManager extends AbstractReactiveTransaction
private ReactiveMongoDatabaseFactory getRequiredDatabaseFactory() {
Assert.state(databaseFactory != null,
"ReactiveMongoTransactionManager operates upon a ReactiveMongoDatabaseFactory. Did you forget to provide one? It's required.");
"ReactiveMongoTransactionManager operates upon a ReactiveMongoDatabaseFactory; Did you forget to provide one; It's required");
return databaseFactory;
}
@@ -401,7 +361,7 @@ public class ReactiveMongoTransactionManager extends AbstractReactiveTransaction
debugString += String.format("causallyConsistent = %s, ", session.isCausallyConsistent());
debugString += String.format("txActive = %s, ", session.hasActiveTransaction());
debugString += String.format("txNumber = %d, ", session.getServerSession().getTransactionNumber());
debugString += String.format("closed = %d, ", session.getServerSession().isClosed());
debugString += String.format("closed = %b, ", session.getServerSession().isClosed());
debugString += String.format("clusterTime = %s", session.getClusterTime());
} else {
debugString += "id = n/a";
@@ -498,30 +458,22 @@ public class ReactiveMongoTransactionManager extends AbstractReactiveTransaction
private ReactiveMongoResourceHolder getRequiredResourceHolder() {
Assert.state(resourceHolder != null, "ReactiveMongoResourceHolder is required but not present. o_O");
Assert.state(resourceHolder != null, "ReactiveMongoResourceHolder is required but not present; o_O");
return resourceHolder;
}
private ClientSession getRequiredSession() {
ClientSession session = getSession();
Assert.state(session != null, "A Session is required but it turned out to be null.");
Assert.state(session != null, "A Session is required but it turned out to be null");
return session;
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.support.SmartTransactionObject#isRollbackOnly()
*/
@Override
public boolean isRollbackOnly() {
return this.resourceHolder != null && this.resourceHolder.isRollbackOnly();
}
/*
* (non-Javadoc)
* @see org.springframework.transaction.support.SmartTransactionObject#flush()
*/
@Override
public void flush() {
throw new UnsupportedOperationException("flush() not supported");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018-2019 the original author or authors.
* Copyright 2018-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -35,7 +35,7 @@ import com.mongodb.session.ClientSession;
/**
* {@link MethodInterceptor} implementation looking up and invoking an alternative target method having
* {@link ClientSession} as its first argument. This allows seamless integration with the existing code base.
* <p />
* <br />
* The {@link MethodInterceptor} is aware of methods on {@code MongoCollection} that my return new instances of itself
* like (eg. {@link com.mongodb.reactivestreams.client.MongoCollection#withWriteConcern(WriteConcern)} and decorate them
* if not already proxied.
@@ -76,13 +76,13 @@ public class SessionAwareMethodInterceptor<D, C> implements MethodInterceptor {
Class<D> databaseType, ClientSessionOperator<D> databaseDecorator, Class<C> collectionType,
ClientSessionOperator<C> collectionDecorator) {
Assert.notNull(session, "ClientSession must not be null!");
Assert.notNull(target, "Target must not be null!");
Assert.notNull(sessionType, "SessionType must not be null!");
Assert.notNull(databaseType, "Database type must not be null!");
Assert.notNull(databaseDecorator, "Database ClientSessionOperator must not be null!");
Assert.notNull(collectionType, "Collection type must not be null!");
Assert.notNull(collectionDecorator, "Collection ClientSessionOperator must not be null!");
Assert.notNull(session, "ClientSession must not be null");
Assert.notNull(target, "Target must not be null");
Assert.notNull(sessionType, "SessionType must not be null");
Assert.notNull(databaseType, "Database type must not be null");
Assert.notNull(databaseDecorator, "Database ClientSessionOperator must not be null");
Assert.notNull(collectionType, "Collection type must not be null");
Assert.notNull(collectionDecorator, "Collection ClientSessionOperator must not be null");
this.session = session;
this.target = target;
@@ -95,10 +95,6 @@ public class SessionAwareMethodInterceptor<D, C> implements MethodInterceptor {
this.sessionType = sessionType;
}
/*
* (non-Javadoc)
* @see org.aopalliance.intercept.MethodInterceptor(org.aopalliance.intercept.MethodInvocation)
*/
@Nullable
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018-2019 the original author or authors.
* Copyright 2018-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,13 +15,20 @@
*/
package org.springframework.data.mongodb;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
/**
* {@link SessionSynchronization} is used along with {@link org.springframework.data.mongodb.core.MongoTemplate} to
* define in which type of transactions to participate if any.
* {@link SessionSynchronization} is used along with {@code MongoTemplate} to define in which type of transactions to
* participate if any.
*
* @author Christoph Strobl
* @author Mark Paluch
* @since 2.1
* @see MongoTemplate#setSessionSynchronization(SessionSynchronization)
* @see MongoDatabaseUtils#getDatabase(MongoDatabaseFactory, SessionSynchronization)
* @see ReactiveMongoTemplate#setSessionSynchronization(SessionSynchronization)
* @see ReactiveMongoDatabaseUtils#getDatabase(ReactiveMongoDatabaseFactory, SessionSynchronization)
*/
public enum SessionSynchronization {
@@ -34,5 +41,12 @@ public enum SessionSynchronization {
/**
* Synchronize with native MongoDB transactions initiated via {@link MongoTransactionManager}.
*/
ON_ACTUAL_TRANSACTION;
ON_ACTUAL_TRANSACTION,
/**
* Do not participate in ongoing transactions.
*
* @since 3.2.5
*/
NEVER;
}

View File

@@ -0,0 +1,77 @@
/*
* Copyright 2020-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.util.Version;
import org.springframework.util.StringUtils;
import com.mongodb.MongoDriverInformation;
/**
* Class that exposes the SpringData MongoDB specific information like the current {@link Version} or
* {@link MongoDriverInformation driver information}.
*
* @author Christoph Strobl
* @since 3.0
*/
public class SpringDataMongoDB {
private static final Log LOGGER = LogFactory.getLog(SpringDataMongoDB.class);
private static final Version FALLBACK_VERSION = new Version(3);
private static final MongoDriverInformation DRIVER_INFORMATION = MongoDriverInformation
.builder(MongoDriverInformation.builder().build()).driverName("spring-data").build();
/**
* Obtain the SpringData MongoDB specific driver information.
*
* @return never {@literal null}.
*/
public static MongoDriverInformation driverInformation() {
return DRIVER_INFORMATION;
}
/**
* Fetches the "Implementation-Version" manifest attribute from the jar file.
* <br />
* Note that some ClassLoaders do not expose the package metadata, hence this class might not be able to determine the
* version in all environments. In this case the current Major version is returned as a fallback.
*
* @return never {@literal null}.
*/
public static Version version() {
Package pkg = SpringDataMongoDB.class.getPackage();
String versionString = (pkg != null ? pkg.getImplementationVersion() : null);
if (!StringUtils.hasText(versionString)) {
LOGGER.debug("Unable to find Spring Data MongoDB version.");
return FALLBACK_VERSION;
}
try {
return Version.parse(versionString);
} catch (Exception e) {
LOGGER.debug(String.format("Cannot read Spring Data MongoDB version '%s'.", versionString));
}
return FALLBACK_VERSION;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2019 the original author or authors.
* Copyright 2010-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -0,0 +1,110 @@
/*
* Copyright 2022-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.aot;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.springframework.aot.generate.GenerationContext;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.TypeReference;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.data.annotation.Reference;
import org.springframework.data.mongodb.core.convert.LazyLoadingProxyFactory;
import org.springframework.data.mongodb.core.convert.LazyLoadingProxyFactory.LazyLoadingInterceptor;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.DocumentReference;
import org.springframework.data.util.TypeUtils;
/**
* @author Christoph Strobl
* @since 4.0
*/
public class LazyLoadingProxyAotProcessor {
private boolean generalLazyLoadingProxyContributed = false;
public void registerLazyLoadingProxyIfNeeded(Class<?> type, GenerationContext generationContext) {
Set<Field> refFields = getFieldsWithAnnotationPresent(type, Reference.class);
if (refFields.isEmpty()) {
return;
}
refFields.stream() //
.filter(LazyLoadingProxyAotProcessor::isLazyLoading) //
.forEach(field -> {
if (!generalLazyLoadingProxyContributed) {
generationContext.getRuntimeHints().proxies().registerJdkProxy(
TypeReference.of(org.springframework.data.mongodb.core.convert.LazyLoadingProxy.class),
TypeReference.of(org.springframework.aop.SpringProxy.class),
TypeReference.of(org.springframework.aop.framework.Advised.class),
TypeReference.of(org.springframework.core.DecoratingProxy.class));
generalLazyLoadingProxyContributed = true;
}
if (field.getType().isInterface()) {
List<Class<?>> interfaces = new ArrayList<>(
TypeUtils.resolveTypesInSignature(ResolvableType.forField(field, type)));
interfaces.add(0, org.springframework.data.mongodb.core.convert.LazyLoadingProxy.class);
interfaces.add(org.springframework.aop.SpringProxy.class);
interfaces.add(org.springframework.aop.framework.Advised.class);
interfaces.add(org.springframework.core.DecoratingProxy.class);
generationContext.getRuntimeHints().proxies().registerJdkProxy(interfaces.toArray(Class[]::new));
} else {
Class<?> proxyClass = LazyLoadingProxyFactory.resolveProxyType(field.getType(),
() -> LazyLoadingInterceptor.none());
// see: spring-projects/spring-framework/issues/29309
generationContext.getRuntimeHints().reflection().registerType(proxyClass,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS);
}
});
}
private static boolean isLazyLoading(Field field) {
if (AnnotatedElementUtils.isAnnotated(field, DBRef.class)) {
return AnnotatedElementUtils.findMergedAnnotation(field, DBRef.class).lazy();
}
if (AnnotatedElementUtils.isAnnotated(field, DocumentReference.class)) {
return AnnotatedElementUtils.findMergedAnnotation(field, DocumentReference.class).lazy();
}
return false;
}
private static Set<Field> getFieldsWithAnnotationPresent(Class<?> type, Class<? extends Annotation> annotation) {
Set<Field> fields = new LinkedHashSet<>();
for (Field field : type.getDeclaredFields()) {
if (MergedAnnotations.from(field).get(annotation).isPresent()) {
fields.add(field);
}
}
return fields;
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright 2022-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.aot;
import java.util.function.Predicate;
import org.springframework.data.mongodb.core.mapping.MongoSimpleTypes;
import org.springframework.data.util.ReactiveWrappers;
import org.springframework.data.util.ReactiveWrappers.ReactiveLibrary;
import org.springframework.data.util.TypeUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
/**
* @author Christoph Strobl
* @since 4.0
*/
public class MongoAotPredicates {
public static final Predicate<Class<?>> IS_SIMPLE_TYPE = (type) -> MongoSimpleTypes.HOLDER.isSimpleType(type) || TypeUtils.type(type).isPartOf("org.bson");
public static final Predicate<ReactiveLibrary> IS_REACTIVE_LIBARARY_AVAILABLE = (lib) -> ReactiveWrappers.isAvailable(lib);
public static final Predicate<ClassLoader> IS_SYNC_CLIENT_PRESENT = (classLoader) -> ClassUtils.isPresent("com.mongodb.client.MongoClient", classLoader);
public static boolean isReactorPresent() {
return IS_REACTIVE_LIBARARY_AVAILABLE.test(ReactiveWrappers.ReactiveLibrary.PROJECT_REACTOR);
}
public static boolean isSyncClientPresent(@Nullable ClassLoader classLoader) {
return IS_SYNC_CLIENT_PRESENT.test(classLoader);
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright 2022-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.aot;
import org.springframework.aot.generate.GenerationContext;
import org.springframework.core.ResolvableType;
import org.springframework.data.aot.ManagedTypesBeanRegistrationAotProcessor;
import org.springframework.data.mongodb.MongoManagedTypes;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
/**
* @author Christoph Strobl
* @since 2022/06
*/
class MongoManagedTypesBeanRegistrationAotProcessor extends ManagedTypesBeanRegistrationAotProcessor {
private final LazyLoadingProxyAotProcessor lazyLoadingProxyAotProcessor = new LazyLoadingProxyAotProcessor();
public MongoManagedTypesBeanRegistrationAotProcessor() {
setModuleIdentifier("mongo");
}
@Override
protected boolean isMatch(@Nullable Class<?> beanType, @Nullable String beanName) {
return isMongoManagedTypes(beanType) || super.isMatch(beanType, beanName);
}
protected boolean isMongoManagedTypes(@Nullable Class<?> beanType) {
return beanType != null && ClassUtils.isAssignable(MongoManagedTypes.class, beanType);
}
@Override
protected void contributeType(ResolvableType type, GenerationContext generationContext) {
if (MongoAotPredicates.IS_SIMPLE_TYPE.test(type.toClass())) {
return;
}
super.contributeType(type, generationContext);
lazyLoadingProxyAotProcessor.registerLazyLoadingProxyIfNeeded(type.toClass(), generationContext);
}
}

View File

@@ -0,0 +1,83 @@
/*
* Copyright 2022-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.aot;
import static org.springframework.data.mongodb.aot.MongoAotPredicates.*;
import java.util.Arrays;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.aot.hint.TypeReference;
import org.springframework.data.mongodb.core.mapping.event.AfterConvertCallback;
import org.springframework.data.mongodb.core.mapping.event.AfterSaveCallback;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertCallback;
import org.springframework.data.mongodb.core.mapping.event.BeforeSaveCallback;
import org.springframework.data.mongodb.core.mapping.event.ReactiveAfterConvertCallback;
import org.springframework.data.mongodb.core.mapping.event.ReactiveAfterSaveCallback;
import org.springframework.data.mongodb.core.mapping.event.ReactiveBeforeConvertCallback;
import org.springframework.data.mongodb.core.mapping.event.ReactiveBeforeSaveCallback;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
/**
* {@link RuntimeHintsRegistrar} for repository types and entity callbacks.
*
* @author Christoph Strobl
* @author Mark Paluch
* @since 4.0
*/
class MongoRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.reflection().registerTypes(
Arrays.asList(TypeReference.of(BeforeConvertCallback.class), TypeReference.of(BeforeSaveCallback.class),
TypeReference.of(AfterConvertCallback.class), TypeReference.of(AfterSaveCallback.class)),
builder -> builder.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_METHODS));
registerTransactionProxyHints(hints, classLoader);
if (isReactorPresent()) {
hints.reflection()
.registerTypes(Arrays.asList(TypeReference.of(ReactiveBeforeConvertCallback.class),
TypeReference.of(ReactiveBeforeSaveCallback.class), TypeReference.of(ReactiveAfterConvertCallback.class),
TypeReference.of(ReactiveAfterSaveCallback.class)),
builder -> builder.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_METHODS));
}
}
private static void registerTransactionProxyHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
if (MongoAotPredicates.isSyncClientPresent(classLoader)
&& ClassUtils.isPresent("org.springframework.aop.SpringProxy", classLoader)) {
hints.proxies().registerJdkProxy(TypeReference.of("com.mongodb.client.MongoDatabase"),
TypeReference.of("org.springframework.aop.SpringProxy"),
TypeReference.of("org.springframework.core.DecoratingProxy"));
hints.proxies().registerJdkProxy(TypeReference.of("com.mongodb.client.MongoCollection"),
TypeReference.of("org.springframework.aop.SpringProxy"),
TypeReference.of("org.springframework.core.DecoratingProxy"));
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018-2019 the original author or authors.
* Copyright 2018-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,17 +17,20 @@ package org.springframework.data.mongodb.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.SpringDataMongoDB;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDbFactory;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.lang.Nullable;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoClientSettings.Builder;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
/**
* Base class for Spring Data MongoDB configuration using JavaConfig with {@link com.mongodb.client.MongoClient}.
@@ -35,77 +38,74 @@ import com.mongodb.client.MongoClient;
* @author Christoph Strobl
* @since 2.1
* @see MongoConfigurationSupport
* @see AbstractMongoConfiguration
*/
@Configuration
@Configuration(proxyBeanMethods = false)
public abstract class AbstractMongoClientConfiguration extends MongoConfigurationSupport {
/**
* Return the {@link MongoClient} instance to connect to. Annotate with {@link Bean} in case you want to expose a
* {@link MongoClient} instance to the {@link org.springframework.context.ApplicationContext}.
* {@link MongoClient} instance to the {@link org.springframework.context.ApplicationContext}. <br />
* Override {@link #mongoClientSettings()} to configure connection details.
*
* @return
* @return never {@literal null}.
* @see #mongoClientSettings()
* @see #configureClientSettings(Builder)
*/
public abstract MongoClient mongoClient();
public MongoClient mongoClient() {
return createMongoClient(mongoClientSettings());
}
/**
* Creates a {@link MongoTemplate}.
*
* @return
* @see #mongoDbFactory()
* @see #mappingMongoConverter(MongoDatabaseFactory, MongoCustomConversions, MongoMappingContext)
*/
@Bean
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongoDbFactory(), mappingMongoConverter());
public MongoTemplate mongoTemplate(MongoDatabaseFactory databaseFactory, MappingMongoConverter converter) {
return new MongoTemplate(databaseFactory, converter);
}
/**
* Creates a {@link SimpleMongoDbFactory} to be used by the {@link MongoTemplate}. Will use the {@link MongoClient}
* instance configured in {@link #mongoClient()}.
* Creates a {@link org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory} to be used by the
* {@link MongoTemplate}. Will use the {@link MongoClient} instance configured in {@link #mongoClient()}.
*
* @see #mongoClient()
* @see #mongoTemplate()
* @return
* @see #mongoTemplate(MongoDatabaseFactory, MappingMongoConverter)
*/
@Bean
public MongoDbFactory mongoDbFactory() {
return new SimpleMongoClientDbFactory(mongoClient(), getDatabaseName());
}
/**
* Return the base package to scan for mapped {@link Document}s. Will return the package name of the configuration
* class' (the concrete class, not this one here) by default. So if you have a {@code com.acme.AppConfig} extending
* {@link AbstractMongoClientConfiguration} the base package will be considered {@code com.acme} unless the method is
* overridden to implement alternate behavior.
*
* @return the base package to scan for mapped {@link Document} classes or {@literal null} to not enable scanning for
* entities.
* @deprecated use {@link #getMappingBasePackages()} instead.
*/
@Deprecated
@Nullable
protected String getMappingBasePackage() {
Package mappingBasePackage = getClass().getPackage();
return mappingBasePackage == null ? null : mappingBasePackage.getName();
public MongoDatabaseFactory mongoDbFactory() {
return new SimpleMongoClientDatabaseFactory(mongoClient(), getDatabaseName());
}
/**
* Creates a {@link MappingMongoConverter} using the configured {@link #mongoDbFactory()} and
* {@link #mongoMappingContext()}. Will get {@link #customConversions()} applied.
* {@link #mongoMappingContext(MongoCustomConversions, org.springframework.data.mongodb.MongoManagedTypes)}. Will get {@link #customConversions()} applied.
*
* @see #customConversions()
* @see #mongoMappingContext()
* @see #mongoMappingContext(MongoCustomConversions, org.springframework.data.mongodb.MongoManagedTypes)
* @see #mongoDbFactory()
* @return
* @throws Exception
*/
@Bean
public MappingMongoConverter mappingMongoConverter() throws Exception {
public MappingMongoConverter mappingMongoConverter(MongoDatabaseFactory databaseFactory,
MongoCustomConversions customConversions, MongoMappingContext mappingContext) {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory());
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext());
converter.setCustomConversions(customConversions());
DbRefResolver dbRefResolver = new DefaultDbRefResolver(databaseFactory);
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mappingContext);
converter.setCustomConversions(customConversions);
converter.setCodecRegistryProvider(databaseFactory);
return converter;
}
/**
* Create the Reactive Streams {@link com.mongodb.reactivestreams.client.MongoClient} instance with given
* {@link MongoClientSettings}.
*
* @return never {@literal null}.
* @since 3.0
*/
protected MongoClient createMongoClient(MongoClientSettings settings) {
return MongoClients.create(settings, SpringDataMongoDB.driverInformation());
}
}

View File

@@ -1,118 +0,0 @@
/*
* Copyright 2011-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.lang.Nullable;
import com.mongodb.MongoClient;
/**
* Base class for Spring Data MongoDB configuration using JavaConfig with {@link com.mongodb.MongoClient}.
* <p />
* <strong>INFO:</strong>In case you want to use {@link com.mongodb.client.MongoClients} for configuration please refer
* to {@link AbstractMongoClientConfiguration}.
*
* @author Mark Pollack
* @author Oliver Gierke
* @author Thomas Darimont
* @author Ryan Tenney
* @author Christoph Strobl
* @author Mark Paluch
* @see MongoConfigurationSupport
* @see AbstractMongoClientConfiguration
*/
@Configuration
public abstract class AbstractMongoConfiguration extends MongoConfigurationSupport {
/**
* Return the {@link MongoClient} instance to connect to. Annotate with {@link Bean} in case you want to expose a
* {@link MongoClient} instance to the {@link org.springframework.context.ApplicationContext}.
*
* @return
*/
public abstract MongoClient mongoClient();
/**
* Creates a {@link MongoTemplate}.
*
* @return
*/
@Bean
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongoDbFactory(), mappingMongoConverter());
}
/**
* Creates a {@link SimpleMongoDbFactory} to be used by the {@link MongoTemplate}. Will use the {@link MongoClient}
* instance configured in {@link #mongoClient()}.
*
* @see #mongoClient()
* @see #mongoTemplate()
* @return
*/
@Bean
public MongoDbFactory mongoDbFactory() {
return new SimpleMongoDbFactory(mongoClient(), getDatabaseName());
}
/**
* Return the base package to scan for mapped {@link Document}s. Will return the package name of the configuration
* class' (the concrete class, not this one here) by default. So if you have a {@code com.acme.AppConfig} extending
* {@link AbstractMongoConfiguration} the base package will be considered {@code com.acme} unless the method is
* overridden to implement alternate behavior.
*
* @return the base package to scan for mapped {@link Document} classes or {@literal null} to not enable scanning for
* entities.
* @deprecated use {@link #getMappingBasePackages()} instead.
*/
@Deprecated
@Nullable
protected String getMappingBasePackage() {
Package mappingBasePackage = getClass().getPackage();
return mappingBasePackage == null ? null : mappingBasePackage.getName();
}
/**
* Creates a {@link MappingMongoConverter} using the configured {@link #mongoDbFactory()} and
* {@link #mongoMappingContext()}. Will get {@link #customConversions()} applied.
*
* @see #customConversions()
* @see #mongoMappingContext()
* @see #mongoDbFactory()
* @return
* @throws Exception
*/
@Bean
public MappingMongoConverter mappingMongoConverter() throws Exception {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory());
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext());
converter.setCustomConversions(customConversions());
return converter;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016-2019 the original author or authors.
* Copyright 2016-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,13 +18,19 @@ package org.springframework.data.mongodb.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.ReactiveMongoDatabaseFactory;
import org.springframework.data.mongodb.SpringDataMongoDB;
import org.springframework.data.mongodb.core.ReactiveMongoOperations;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.data.mongodb.core.SimpleReactiveMongoDatabaseFactory;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import org.springframework.data.mongodb.core.convert.NoOpDbRefResolver;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoClientSettings.Builder;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoClients;
/**
* Base class for reactive Spring Data MongoDB configuration using JavaConfig.
@@ -34,25 +40,33 @@ import com.mongodb.reactivestreams.client.MongoClient;
* @since 2.0
* @see MongoConfigurationSupport
*/
@Configuration
@Configuration(proxyBeanMethods = false)
public abstract class AbstractReactiveMongoConfiguration extends MongoConfigurationSupport {
/**
* Return the Reactive Streams {@link MongoClient} instance to connect to. Annotate with {@link Bean} in case you want
* to expose a {@link MongoClient} instance to the {@link org.springframework.context.ApplicationContext}.
* to expose a {@link MongoClient} instance to the {@link org.springframework.context.ApplicationContext}. <br />
* Override {@link #mongoClientSettings()} to configure connection details.
*
* @return never {@literal null}.
* @see #mongoClientSettings()
* @see #configureClientSettings(Builder)
*/
public abstract MongoClient reactiveMongoClient();
public MongoClient reactiveMongoClient() {
return createReactiveMongoClient(mongoClientSettings());
}
/**
* Creates {@link ReactiveMongoOperations}.
*
* @see #reactiveMongoDbFactory()
* @see #mappingMongoConverter(ReactiveMongoDatabaseFactory, MongoCustomConversions, MongoMappingContext)
* @return never {@literal null}.
*/
@Bean
public ReactiveMongoOperations reactiveMongoTemplate() throws Exception {
return new ReactiveMongoTemplate(reactiveMongoDbFactory(), mappingMongoConverter());
public ReactiveMongoTemplate reactiveMongoTemplate(ReactiveMongoDatabaseFactory databaseFactory,
MappingMongoConverter mongoConverter) {
return new ReactiveMongoTemplate(databaseFactory, mongoConverter);
}
/**
@@ -60,7 +74,7 @@ public abstract class AbstractReactiveMongoConfiguration extends MongoConfigurat
* {@link MongoClient} instance configured in {@link #reactiveMongoClient()}.
*
* @see #reactiveMongoClient()
* @see #reactiveMongoTemplate()
* @see #reactiveMongoTemplate(ReactiveMongoDatabaseFactory, MappingMongoConverter)
* @return never {@literal null}.
*/
@Bean
@@ -70,20 +84,31 @@ public abstract class AbstractReactiveMongoConfiguration extends MongoConfigurat
/**
* Creates a {@link MappingMongoConverter} using the configured {@link #reactiveMongoDbFactory()} and
* {@link #mongoMappingContext()}. Will get {@link #customConversions()} applied.
* {@link #mongoMappingContext(MongoCustomConversions, org.springframework.data.mongodb.MongoManagedTypes)}. Will get {@link #customConversions()} applied.
*
* @see #customConversions()
* @see #mongoMappingContext()
* @see #mongoMappingContext(MongoCustomConversions, org.springframework.data.mongodb.MongoManagedTypes)
* @see #reactiveMongoDbFactory()
* @return never {@literal null}.
* @throws Exception
*/
@Bean
public MappingMongoConverter mappingMongoConverter() throws Exception {
public MappingMongoConverter mappingMongoConverter(ReactiveMongoDatabaseFactory databaseFactory,
MongoCustomConversions customConversions, MongoMappingContext mappingContext) {
MappingMongoConverter converter = new MappingMongoConverter(NoOpDbRefResolver.INSTANCE, mongoMappingContext());
converter.setCustomConversions(customConversions());
MappingMongoConverter converter = new MappingMongoConverter(NoOpDbRefResolver.INSTANCE, mappingContext);
converter.setCustomConversions(customConversions);
converter.setCodecRegistryProvider(databaseFactory);
return converter;
}
/**
* Create the Reactive Streams {@link MongoClient} instance with given {@link MongoClientSettings}.
*
* @return never {@literal null}.
* @since 3.0
*/
protected MongoClient createReactiveMongoClient(MongoClientSettings settings) {
return MongoClients.create(settings, SpringDataMongoDB.driverInformation());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2019 the original author or authors.
* Copyright 2011-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -0,0 +1,42 @@
/*
* Copyright 2019-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.config;
import java.beans.PropertyEditorSupport;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import com.mongodb.ConnectionString;
/**
* Parse a {@link String} to a {@link com.mongodb.ConnectionString}.
*
* @author Christoph Strobl
* @since 3.0
*/
public class ConnectionStringPropertyEditor extends PropertyEditorSupport {
@Override
public void setAsText(@Nullable String connectionString) {
if (!StringUtils.hasText(connectionString)) {
return;
}
setValue(new ConnectionString(connectionString));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2019 the original author or authors.
* Copyright 2013-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,29 +42,29 @@ public @interface EnableMongoAuditing {
/**
* Configures the {@link AuditorAware} bean to be used to lookup the current principal.
*
* @return
* @return empty {@link String} by default.
*/
String auditorAwareRef() default "";
/**
* Configures whether the creation and modification dates are set. Defaults to {@literal true}.
*
* @return
* @return {@literal true} by default.
*/
boolean setDates() default true;
/**
* Configures whether the entity shall be marked as modified on creation. Defaults to {@literal true}.
*
* @return
* @return {@literal true} by default.
*/
boolean modifyOnCreate() default true;
/**
* Configures a {@link DateTimeProvider} bean name that allows customizing the {@link org.joda.time.DateTime} to be
* used for setting creation and modification dates.
* Configures a {@link DateTimeProvider} bean name that allows customizing the timestamp to be used for setting
* creation and modification dates.
*
* @return
* @return empty {@link String} by default.
*/
String dateTimeProviderRef() default "";
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright 2020-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.config;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
import org.springframework.data.auditing.DateTimeProvider;
import org.springframework.data.domain.ReactiveAuditorAware;
/**
* Annotation to enable auditing in MongoDB using reactive infrastructure via annotation configuration.
*
* @author Mark Paluch
* @since 3.1
*/
@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(ReactiveMongoAuditingRegistrar.class)
public @interface EnableReactiveMongoAuditing {
/**
* Configures the {@link ReactiveAuditorAware} bean to be used to lookup the current principal.
*
* @return empty {@link String} by default.
*/
String auditorAwareRef() default "";
/**
* Configures whether the creation and modification dates are set. Defaults to {@literal true}.
*
* @return {@literal true} by default.
*/
boolean setDates() default true;
/**
* Configures whether the entity shall be marked as modified on creation. Defaults to {@literal true}.
*
* @return {@literal true} by default.
*/
boolean modifyOnCreate() default true;
/**
* Configures a {@link DateTimeProvider} bean name that allows customizing the timestamp to be used for setting
* creation and modification dates.
*
* @return empty {@link String} by default.
*/
String dateTimeProviderRef() default "";
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2019 the original author or authors.
* Copyright 2015-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2019 the original author or authors.
* Copyright 2013-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,10 +34,6 @@ import org.w3c.dom.Element;
*/
class GridFsTemplateParser extends AbstractBeanDefinitionParser {
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.xml.AbstractBeanDefinitionParser#resolveId(org.w3c.dom.Element, org.springframework.beans.factory.support.AbstractBeanDefinition, org.springframework.beans.factory.xml.ParserContext)
*/
@Override
protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext)
throws BeanDefinitionStoreException {
@@ -46,10 +42,6 @@ class GridFsTemplateParser extends AbstractBeanDefinitionParser {
return StringUtils.hasText(id) ? id : BeanNames.GRID_FS_TEMPLATE_BEAN_NAME;
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.xml.AbstractBeanDefinitionParser#parseInternal(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext)
*/
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2019 the original author or authors.
* Copyright 2011-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,7 +24,6 @@ import java.util.List;
import java.util.Set;
import org.springframework.beans.BeanMetadataElement;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.RuntimeBeanReference;
@@ -64,6 +63,7 @@ import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
/**
@@ -80,7 +80,7 @@ import org.w3c.dom.Element;
public class MappingMongoConverterParser implements BeanDefinitionParser {
private static final String BASE_PACKAGE = "base-package";
private static final boolean JSR_303_PRESENT = ClassUtils.isPresent("javax.validation.Validator",
private static final boolean JSR_303_PRESENT = ClassUtils.isPresent("jakarta.validation.Validator",
MappingMongoConverterParser.class.getClassLoader());
/* (non-Javadoc)
@@ -96,6 +96,9 @@ public class MappingMongoConverterParser implements BeanDefinitionParser {
String id = element.getAttribute(AbstractBeanDefinitionParser.ID_ATTRIBUTE);
id = StringUtils.hasText(id) ? id : DEFAULT_CONVERTER_BEAN_NAME;
String autoIndexCreation = element.getAttribute("auto-index-creation");
boolean autoIndexCreationEnabled = StringUtils.hasText(autoIndexCreation) && Boolean.valueOf(autoIndexCreation);
parserContext.pushContainingComponent(new CompositeComponentDefinition("Mapping Mongo Converter", element));
BeanDefinition conversionsDefinition = getCustomConversions(element, parserContext);
@@ -132,9 +135,7 @@ public class MappingMongoConverterParser implements BeanDefinitionParser {
new BeanComponentDefinition(indexOperationsProviderBuilder.getBeanDefinition(), "indexOperationsProvider"));
}
try {
registry.getBeanDefinition(INDEX_HELPER_BEAN_NAME);
} catch (NoSuchBeanDefinitionException ignored) {
if (!registry.containsBeanDefinition(INDEX_HELPER_BEAN_NAME)) {
BeanDefinitionBuilder indexHelperBuilder = BeanDefinitionBuilder
.genericBeanDefinition(MongoPersistentEntityIndexCreator.class);
@@ -148,7 +149,7 @@ public class MappingMongoConverterParser implements BeanDefinitionParser {
BeanDefinition validatingMongoEventListener = potentiallyCreateValidatingMongoEventListener(element, parserContext);
if (validatingMongoEventListener != null) {
if (validatingMongoEventListener != null && !registry.containsBeanDefinition(VALIDATING_EVENT_LISTENER_BEAN_NAME)) {
parserContext.registerBeanComponent(
new BeanComponentDefinition(validatingMongoEventListener, VALIDATING_EVENT_LISTENER_BEAN_NAME));
}
@@ -162,15 +163,16 @@ public class MappingMongoConverterParser implements BeanDefinitionParser {
private BeanDefinition potentiallyCreateValidatingMongoEventListener(Element element, ParserContext parserContext) {
String disableValidation = element.getAttribute("disable-validation");
boolean validationDisabled = StringUtils.hasText(disableValidation) && Boolean.valueOf(disableValidation);
boolean validationDisabled = StringUtils.hasText(disableValidation) && Boolean.parseBoolean(disableValidation);
if (!validationDisabled) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
RuntimeBeanReference validator = getValidator(builder, parserContext);
RuntimeBeanReference validator = getValidator(element, parserContext);
if (validator != null) {
builder.getRawBeanDefinition().setBeanClass(ValidatingMongoEventListener.class);
builder.getRawBeanDefinition().setSource(element);
builder.addConstructorArgValue(validator);
return builder.getBeanDefinition();
@@ -192,13 +194,17 @@ public class MappingMongoConverterParser implements BeanDefinitionParser {
validatorDef.setSource(source);
validatorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
String validatorName = parserContext.getReaderContext().registerWithGeneratedName(validatorDef);
parserContext.registerBeanComponent(new BeanComponentDefinition(validatorDef, validatorName));
return new RuntimeBeanReference(validatorName);
}
public static String potentiallyCreateMappingContext(Element element, ParserContext parserContext,
@Nullable BeanDefinition conversionsDefinition, @Nullable String converterId) {
return potentiallyCreateMappingContext(element, parserContext, conversionsDefinition, converterId, false);
}
public static String potentiallyCreateMappingContext(Element element, ParserContext parserContext,
@Nullable BeanDefinition conversionsDefinition, @Nullable String converterId, boolean autoIndexCreation) {
String ctxRef = element.getAttribute("mapping-context-ref");
@@ -226,6 +232,8 @@ public class MappingMongoConverterParser implements BeanDefinitionParser {
mappingContextBuilder.addPropertyValue("simpleTypeHolder", simpleTypesDefinition);
}
mappingContextBuilder.addPropertyValue("autoIndexCreation", autoIndexCreation);
parseFieldNamingStrategy(element, parserContext.getReaderContext(), mappingContextBuilder);
ctxRef = converterId == null || DEFAULT_CONVERTER_BEAN_NAME.equals(converterId) ? MAPPING_CONTEXT_BEAN_NAME
@@ -245,7 +253,7 @@ public class MappingMongoConverterParser implements BeanDefinitionParser {
&& Boolean.parseBoolean(abbreviateFieldNames);
if (fieldNamingStrategyReferenced && abbreviationActivated) {
context.error("Field name abbreviation cannot be activated if a field-naming-strategy-ref is configured!",
context.error("Field name abbreviation cannot be activated if a field-naming-strategy-ref is configured",
element);
return;
}
@@ -366,10 +374,6 @@ public class MappingMongoConverterParser implements BeanDefinitionParser {
this.delegates = new HashSet<>(Arrays.asList(filters));
}
/*
* (non-Javadoc)
* @see org.springframework.core.type.filter.TypeFilter#match(org.springframework.core.type.classreading.MetadataReader, org.springframework.core.type.classreading.MetadataReaderFactory)
*/
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,28 +47,16 @@ public class MongoAuditingBeanDefinitionParser extends AbstractSingleBeanDefinit
private static boolean PROJECT_REACTOR_AVAILABLE = ClassUtils.isPresent("reactor.core.publisher.Mono",
MongoAuditingRegistrar.class.getClassLoader());
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser#getBeanClass(org.w3c.dom.Element)
*/
@Override
protected Class<?> getBeanClass(Element element) {
return AuditingEntityCallback.class;
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.xml.AbstractBeanDefinitionParser#shouldGenerateId()
*/
@Override
protected boolean shouldGenerateId() {
return true;
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser#doParse(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext, org.springframework.beans.factory.support.BeanDefinitionBuilder)
*/
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2019 the original author or authors.
* Copyright 2013-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,25 +17,17 @@ package org.springframework.data.mongodb.config;
import java.lang.annotation.Annotation;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.Ordered;
import org.springframework.data.auditing.IsNewAwareAuditingHandler;
import org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport;
import org.springframework.data.auditing.config.AuditingConfiguration;
import org.springframework.data.config.ParsingUtils;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.core.mapping.event.AuditingEntityCallback;
import org.springframework.data.mongodb.core.mapping.event.ReactiveAuditingEntityCallback;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/**
* {@link ImportBeanDefinitionRegistrar} to enable {@link EnableMongoAuditing} annotation.
@@ -43,71 +35,42 @@ import org.springframework.util.ClassUtils;
* @author Thomas Darimont
* @author Oliver Gierke
* @author Mark Paluch
* @author Christoph Strobl
*/
class MongoAuditingRegistrar extends AuditingBeanDefinitionRegistrarSupport {
class MongoAuditingRegistrar extends AuditingBeanDefinitionRegistrarSupport implements Ordered {
private static boolean PROJECT_REACTOR_AVAILABLE = ClassUtils.isPresent("reactor.core.publisher.Mono",
MongoAuditingRegistrar.class.getClassLoader());
/*
* (non-Javadoc)
* @see org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport#getAnnotation()
*/
@Override
protected Class<? extends Annotation> getAnnotation() {
return EnableMongoAuditing.class;
}
/*
* (non-Javadoc)
* @see org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport#getAuditingHandlerBeanName()
*/
@Override
protected String getAuditingHandlerBeanName() {
return "mongoAuditingHandler";
}
/*
* (non-Javadoc)
* @see org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport#registerBeanDefinitions(org.springframework.core.type.AnnotationMetadata, org.springframework.beans.factory.support.BeanDefinitionRegistry)
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {
protected void postProcess(BeanDefinitionBuilder builder, AuditingConfiguration configuration,
BeanDefinitionRegistry registry) {
Assert.notNull(annotationMetadata, "AnnotationMetadata must not be null!");
Assert.notNull(registry, "BeanDefinitionRegistry must not be null!");
super.registerBeanDefinitions(annotationMetadata, registry);
builder.setFactoryMethod("from").addConstructorArgReference("mongoMappingContext");
}
/*
* (non-Javadoc)
* @see org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport#getAuditHandlerBeanDefinitionBuilder(org.springframework.data.auditing.config.AuditingConfiguration)
*/
@Override
protected BeanDefinitionBuilder getAuditHandlerBeanDefinitionBuilder(AuditingConfiguration configuration) {
Assert.notNull(configuration, "AuditingConfiguration must not be null!");
Assert.notNull(configuration, "AuditingConfiguration must not be null");
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(IsNewAwareAuditingHandler.class);
BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(MongoMappingContextLookup.class);
definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
builder.addConstructorArgValue(definition.getBeanDefinition());
return configureDefaultAuditHandlerAttributes(configuration, builder);
return configureDefaultAuditHandlerAttributes(configuration,
BeanDefinitionBuilder.rootBeanDefinition(IsNewAwareAuditingHandler.class));
}
/*
* (non-Javadoc)
* @see org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport#registerAuditListener(org.springframework.beans.factory.config.BeanDefinition, org.springframework.beans.factory.support.BeanDefinitionRegistry)
*/
@Override
protected void registerAuditListenerBeanDefinition(BeanDefinition auditingHandlerDefinition,
BeanDefinitionRegistry registry) {
Assert.notNull(auditingHandlerDefinition, "BeanDefinition must not be null!");
Assert.notNull(registry, "BeanDefinitionRegistry must not be null!");
Assert.notNull(auditingHandlerDefinition, "BeanDefinition must not be null");
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
BeanDefinitionBuilder listenerBeanDefinitionBuilder = BeanDefinitionBuilder
.rootBeanDefinition(AuditingEntityCallback.class);
@@ -116,68 +79,10 @@ class MongoAuditingRegistrar extends AuditingBeanDefinitionRegistrarSupport {
registerInfrastructureBeanWithId(listenerBeanDefinitionBuilder.getBeanDefinition(),
AuditingEntityCallback.class.getName(), registry);
if (PROJECT_REACTOR_AVAILABLE) {
registerReactiveAuditingEntityCallback(registry, auditingHandlerDefinition.getSource());
}
}
private void registerReactiveAuditingEntityCallback(BeanDefinitionRegistry registry, Object source) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ReactiveAuditingEntityCallback.class);
builder.addConstructorArgValue(ParsingUtils.getObjectFactoryBeanDefinition(getAuditingHandlerBeanName(), registry));
builder.getRawBeanDefinition().setSource(source);
registerInfrastructureBeanWithId(builder.getBeanDefinition(), ReactiveAuditingEntityCallback.class.getName(),
registry);
}
/**
* Simple helper to be able to wire the {@link MappingContext} from a {@link MappingMongoConverter} bean available in
* the application context.
*
* @author Oliver Gierke
*/
static class MongoMappingContextLookup
implements FactoryBean<MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty>> {
private final MappingMongoConverter converter;
/**
* Creates a new {@link MongoMappingContextLookup} for the given {@link MappingMongoConverter}.
*
* @param converter must not be {@literal null}.
*/
public MongoMappingContextLookup(MappingMongoConverter converter) {
this.converter = converter;
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.FactoryBean#getObject()
*/
@Override
public MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> getObject() throws Exception {
return converter.getMappingContext();
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
*/
@Override
public Class<?> getObjectType() {
return MappingContext.class;
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.FactoryBean#isSingleton()
*/
@Override
public boolean isSingleton() {
return true;
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2019 the original author or authors.
* Copyright 2015-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -35,10 +35,6 @@ import org.w3c.dom.Element;
*/
public class MongoClientParser implements BeanDefinitionParser {
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.xml.BeanDefinitionParser#parse(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext)
*/
public BeanDefinition parse(Element element, ParserContext parserContext) {
Object source = parserContext.extractSource(element);
@@ -50,10 +46,11 @@ public class MongoClientParser implements BeanDefinitionParser {
ParsingUtils.setPropertyValue(builder, element, "port", "port");
ParsingUtils.setPropertyValue(builder, element, "host", "host");
ParsingUtils.setPropertyValue(builder, element, "credentials", "credentials");
ParsingUtils.setPropertyValue(builder, element, "credential", "credential");
ParsingUtils.setPropertyValue(builder, element, "replica-set", "replicaSet");
ParsingUtils.setPropertyValue(builder, element, "connection-string", "connectionString");
MongoParsingUtils.parseMongoClientOptions(element, builder);
MongoParsingUtils.parseReplicaSet(element, builder);
MongoParsingUtils.parseMongoClientSettings(element, builder);
String defaultedId = StringUtils.hasText(id) ? id : BeanNames.MONGO_BEAN_NAME;
@@ -62,22 +59,34 @@ public class MongoClientParser implements BeanDefinitionParser {
BeanComponentDefinition mongoComponent = helper.getComponent(builder, defaultedId);
parserContext.registerBeanComponent(mongoComponent);
BeanComponentDefinition serverAddressPropertyEditor = helper.getComponent(MongoParsingUtils
.getServerAddressPropertyEditorBuilder());
BeanComponentDefinition connectionStringPropertyEditor = helper
.getComponent(MongoParsingUtils.getConnectionStringPropertyEditorBuilder());
parserContext.registerBeanComponent(connectionStringPropertyEditor);
BeanComponentDefinition serverAddressPropertyEditor = helper
.getComponent(MongoParsingUtils.getServerAddressPropertyEditorBuilder());
parserContext.registerBeanComponent(serverAddressPropertyEditor);
BeanComponentDefinition writeConcernEditor = helper.getComponent(MongoParsingUtils
.getWriteConcernPropertyEditorBuilder());
BeanComponentDefinition writeConcernEditor = helper
.getComponent(MongoParsingUtils.getWriteConcernPropertyEditorBuilder());
parserContext.registerBeanComponent(writeConcernEditor);
BeanComponentDefinition readPreferenceEditor = helper.getComponent(MongoParsingUtils
.getReadPreferencePropertyEditorBuilder());
BeanComponentDefinition readConcernEditor = helper
.getComponent(MongoParsingUtils.getReadConcernPropertyEditorBuilder());
parserContext.registerBeanComponent(readConcernEditor);
BeanComponentDefinition readPreferenceEditor = helper
.getComponent(MongoParsingUtils.getReadPreferencePropertyEditorBuilder());
parserContext.registerBeanComponent(readPreferenceEditor);
BeanComponentDefinition credentialsEditor = helper.getComponent(MongoParsingUtils
.getMongoCredentialPropertyEditor());
BeanComponentDefinition credentialsEditor = helper
.getComponent(MongoParsingUtils.getMongoCredentialPropertyEditor());
parserContext.registerBeanComponent(credentialsEditor);
BeanComponentDefinition uuidRepresentationEditor = helper
.getComponent(MongoParsingUtils.getUUidRepresentationEditorBuilder());
parserContext.registerBeanComponent(uuidRepresentationEditor);
parserContext.popAndRegisterContainingComponent();
return mongoComponent.getBeanDefinition();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016-2019 the original author or authors.
* Copyright 2016-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,22 +20,27 @@ import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.bson.UuidRepresentation;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.data.annotation.Persistent;
import org.springframework.data.convert.CustomConversions;
import org.springframework.data.mapping.model.CamelCaseAbbreviatingFieldNamingStrategy;
import org.springframework.data.mapping.model.FieldNamingStrategy;
import org.springframework.data.mapping.model.PropertyNameFieldNamingStrategy;
import org.springframework.data.mongodb.MongoManagedTypes;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions.MongoConverterConfigurationAdapter;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoClientSettings.Builder;
/**
* Base class for Spring Data MongoDB to be extended for JavaConfiguration usage.
*
@@ -72,30 +77,56 @@ public abstract class MongoConfigurationSupport {
*
* @see #getMappingBasePackages()
* @return
* @throws ClassNotFoundException
*/
@Bean
public MongoMappingContext mongoMappingContext() throws ClassNotFoundException {
public MongoMappingContext mongoMappingContext(MongoCustomConversions customConversions,
MongoManagedTypes mongoManagedTypes) {
MongoMappingContext mappingContext = new MongoMappingContext();
mappingContext.setInitialEntitySet(getInitialEntitySet());
mappingContext.setSimpleTypeHolder(customConversions().getSimpleTypeHolder());
mappingContext.setManagedTypes(mongoManagedTypes);
mappingContext.setSimpleTypeHolder(customConversions.getSimpleTypeHolder());
mappingContext.setFieldNamingStrategy(fieldNamingStrategy());
mappingContext.setAutoIndexCreation(autoIndexCreation());
return mappingContext;
}
/**
* @return new instance of {@link MongoManagedTypes}.
* @throws ClassNotFoundException
* @since 4.0
*/
@Bean
public MongoManagedTypes mongoManagedTypes() throws ClassNotFoundException {
return MongoManagedTypes.fromIterable(getInitialEntitySet());
}
/**
* Register custom {@link Converter}s in a {@link CustomConversions} object if required. These
* {@link CustomConversions} will be registered with the {@link #mappingMongoConverter()} and
* {@link #mongoMappingContext()}. Returns an empty {@link MongoCustomConversions} instance by default.
* {@link CustomConversions} will be registered with the
* {@link org.springframework.data.mongodb.core.convert.MappingMongoConverter} and {@link MongoMappingContext}.
* Returns an empty {@link MongoCustomConversions} instance by default.
* <p>
* <strong>NOTE:</strong> Use {@link #configureConverters(MongoConverterConfigurationAdapter)} to configure MongoDB
* native simple types and register custom {@link Converter converters}.
*
* @return must not be {@literal null}.
*/
@Bean
public CustomConversions customConversions() {
return new MongoCustomConversions(Collections.emptyList());
public MongoCustomConversions customConversions() {
return MongoCustomConversions.create(this::configureConverters);
}
/**
* Configuration hook for {@link MongoCustomConversions} creation.
*
* @param converterConfigurationAdapter never {@literal null}.
* @since 2.3
* @see MongoConverterConfigurationAdapter#useNativeDriverJavaTimeCodecs()
* @see MongoConverterConfigurationAdapter#useSpringDataJavaTimeCodecs()
*/
protected void configureConverters(MongoConverterConfigurationAdapter converterConfigurationAdapter) {
}
/**
@@ -118,8 +149,7 @@ public abstract class MongoConfigurationSupport {
}
/**
* Scans the given base package for entities, i.e. MongoDB specific types annotated with {@link Document} and
* {@link Persistent}.
* Scans the given base package for entities, i.e. MongoDB specific types annotated with {@link Document}.
*
* @param basePackage must not be {@literal null}.
* @return
@@ -139,7 +169,6 @@ public abstract class MongoConfigurationSupport {
ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider(
false);
componentProvider.addIncludeFilter(new AnnotationTypeFilter(Document.class));
componentProvider.addIncludeFilter(new AnnotationTypeFilter(Persistent.class));
for (BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) {
@@ -153,8 +182,7 @@ public abstract class MongoConfigurationSupport {
/**
* Configures whether to abbreviate field names for domain objects by configuring a
* {@link CamelCaseAbbreviatingFieldNamingStrategy} on the {@link MongoMappingContext} instance created. For advanced
* customization needs, consider overriding {@link #mappingMongoConverter()}.
* {@link CamelCaseAbbreviatingFieldNamingStrategy} on the {@link MongoMappingContext} instance created.
*
* @return
*/
@@ -177,11 +205,36 @@ public abstract class MongoConfigurationSupport {
* Configure whether to automatically create indices for domain types by deriving the
* {@link org.springframework.data.mongodb.core.index.IndexDefinition} from the entity or not.
*
* @return {@literal true} by default. <br />
* <strong>INFO</strong>: As of 3.x the default will be set to {@literal false}.
* @return {@literal false} by default. <br />
* <strong>INFO</strong>: As of 3.x the default is set to {@literal false}; In 2.x it was {@literal true}.
* @since 2.2
*/
protected boolean autoIndexCreation() {
return true;
return false;
}
/**
* Return the {@link MongoClientSettings} used to create the actual {@literal MongoClient}. <br />
* Override either this method, or use {@link #configureClientSettings(Builder)} to alter the setup.
*
* @return never {@literal null}.
* @since 3.0
*/
protected MongoClientSettings mongoClientSettings() {
MongoClientSettings.Builder builder = MongoClientSettings.builder();
builder.uuidRepresentation(UuidRepresentation.JAVA_LEGACY);
configureClientSettings(builder);
return builder.build();
}
/**
* Configure {@link MongoClientSettings} via its {@link Builder} API.
*
* @param builder never {@literal null}.
* @since 3.0
*/
protected void configureClientSettings(MongoClientSettings.Builder builder) {
// customization hook
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2019 the original author or authors.
* Copyright 2015-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -51,10 +51,6 @@ public class MongoCredentialPropertyEditor extends PropertyEditorSupport {
private static final String OPTIONS_DELIMITER = "?";
private static final String OPTION_VALUE_DELIMITER = "&";
/*
* (non-Javadoc)
* @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
*/
@Override
public void setAsText(@Nullable String text) throws IllegalArgumentException {
@@ -121,7 +117,7 @@ public class MongoCredentialPropertyEditor extends PropertyEditorSupport {
userNameAndPassword[1].toCharArray()));
} else {
throw new IllegalArgumentException(
String.format("Cannot create MongoCredentials for unknown auth mechanism '%s'!", authMechanism));
String.format("Cannot create MongoCredentials for unknown auth mechanism '%s'", authMechanism));
}
}
} else {
@@ -198,7 +194,7 @@ public class MongoCredentialPropertyEditor extends PropertyEditorSupport {
String[] optionArgs = option.split("=");
if (optionArgs.length == 1) {
throw new IllegalArgumentException(String.format("Query parameter '%s' has no value!", optionArgs[0]));
throw new IllegalArgumentException(String.format("Query parameter '%s' has no value", optionArgs[0]));
}
properties.put(optionArgs[0], optionArgs[1]);
@@ -213,21 +209,21 @@ public class MongoCredentialPropertyEditor extends PropertyEditorSupport {
if (source.length != 2) {
throw new IllegalArgumentException(
"Credentials need to specify username and password like in 'username:password@database'!");
"Credentials need to specify username and password like in 'username:password@database'");
}
}
private static void verifyDatabasePresent(String source) {
if (!StringUtils.hasText(source)) {
throw new IllegalArgumentException("Credentials need to specify database like in 'username:password@database'!");
throw new IllegalArgumentException("Credentials need to specify database like in 'username:password@database'");
}
}
private static void verifyUserNamePresent(String[] source) {
if (source.length == 0 || !StringUtils.hasText(source[0])) {
throw new IllegalArgumentException("Credentials need to specify username!");
throw new IllegalArgumentException("Credentials need to specify username");
}
}
@@ -235,7 +231,7 @@ public class MongoCredentialPropertyEditor extends PropertyEditorSupport {
try {
return URLDecoder.decode(it, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("o_O UTF-8 not supported!", e);
throw new IllegalArgumentException("o_O UTF-8 not supported", e);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2019 the original author or authors.
* Copyright 2011-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,14 +32,12 @@ import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.data.config.BeanComponentDefinitionBuilder;
import org.springframework.data.mongodb.core.MongoClientFactoryBean;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
import com.mongodb.Mongo;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoURI;
import com.mongodb.ConnectionString;
/**
* {@link BeanDefinitionParser} to parse {@code db-factory} elements into {@link BeanDefinition}s.
@@ -64,10 +62,6 @@ public class MongoDbFactoryParser extends AbstractBeanDefinitionParser {
MONGO_URI_ALLOWED_ADDITIONAL_ATTRIBUTES = Collections.unmodifiableSet(mongoUriAllowedAdditionalAttributes);
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.xml.AbstractBeanDefinitionParser#resolveId(org.w3c.dom.Element, org.springframework.beans.factory.support.AbstractBeanDefinition, org.springframework.beans.factory.xml.ParserContext)
*/
@Override
protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext)
throws BeanDefinitionStoreException {
@@ -76,18 +70,15 @@ public class MongoDbFactoryParser extends AbstractBeanDefinitionParser {
return StringUtils.hasText(id) ? id : BeanNames.DB_FACTORY_BEAN_NAME;
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.xml.AbstractBeanDefinitionParser#parseInternal(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext)
*/
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
// Common setup
BeanDefinitionBuilder dbFactoryBuilder = BeanDefinitionBuilder.genericBeanDefinition(SimpleMongoDbFactory.class);
BeanDefinitionBuilder dbFactoryBuilder = BeanDefinitionBuilder
.genericBeanDefinition(SimpleMongoClientDatabaseFactory.class);
setPropertyValue(dbFactoryBuilder, element, "write-concern", "writeConcern");
BeanDefinition mongoUri = getMongoUri(element, parserContext);
BeanDefinition mongoUri = getConnectionString(element, parserContext);
if (mongoUri != null) {
@@ -97,7 +88,8 @@ public class MongoDbFactoryParser extends AbstractBeanDefinitionParser {
BeanComponentDefinitionBuilder helper = new BeanComponentDefinitionBuilder(element, parserContext);
String mongoRef = element.getAttribute("mongo-ref");
String mongoRef = element.getAttribute("mongo-client-ref");
String dbname = element.getAttribute("dbname");
// Defaulting
@@ -119,8 +111,8 @@ public class MongoDbFactoryParser extends AbstractBeanDefinitionParser {
}
/**
* Registers a default {@link BeanDefinition} of a {@link Mongo} instance and returns the name under which the
* {@link Mongo} instance was registered under.
* Registers a default {@link BeanDefinition} of a {@link com.mongodb.client.MongoClient} instance and returns the
* name under which the {@link com.mongodb.client.MongoClient} instance was registered under.
*
* @param element must not be {@literal null}.
* @param parserContext must not be {@literal null}.
@@ -136,8 +128,7 @@ public class MongoDbFactoryParser extends AbstractBeanDefinitionParser {
}
/**
* Creates a {@link BeanDefinition} for a {@link MongoURI} or {@link MongoClientURI} depending on configured
* attributes. <br />
* Creates a {@link BeanDefinition} for a {@link ConnectionString} depending on configured attributes. <br />
* Errors when configured element contains {@literal uri} or {@literal client-uri} along with other attributes except
* {@literal write-concern} and/or {@literal id}.
*
@@ -146,11 +137,19 @@ public class MongoDbFactoryParser extends AbstractBeanDefinitionParser {
* @return {@literal null} in case no client-/uri defined.
*/
@Nullable
private BeanDefinition getMongoUri(Element element, ParserContext parserContext) {
private BeanDefinition getConnectionString(Element element, ParserContext parserContext) {
boolean hasClientUri = element.hasAttribute("client-uri");
String type = null;
if (!hasClientUri && !element.hasAttribute("uri")) {
if (element.hasAttribute("client-uri")) {
type = "client-uri";
} else if (element.hasAttribute("connection-string")) {
type = "connection-string";
} else if (element.hasAttribute("uri")) {
type = "uri";
}
if (!StringUtils.hasText(type)) {
return null;
}
@@ -164,16 +163,12 @@ public class MongoDbFactoryParser extends AbstractBeanDefinitionParser {
if (element.getAttributes().getLength() > allowedAttributesCount) {
parserContext.getReaderContext().error(
"Configure either " + (hasClientUri ? "Mongo Client URI" : "Mongo URI") + " or details individually!",
parserContext.getReaderContext().error("Configure either MongoDB " + type + " or details individually",
parserContext.extractSource(element));
}
Class<?> type = MongoClientURI.class;
String uri = hasClientUri ? element.getAttribute("client-uri") : element.getAttribute("uri");
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(type);
builder.addConstructorArgValue(uri);
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ConnectionString.class);
builder.addConstructorArgValue(element.getAttribute(type));
return builder.getBeanDefinition();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2019 the original author or authors.
* Copyright 2011-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2019 the original author or authors.
* Copyright 2011-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,10 +26,6 @@ import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
*/
public class MongoNamespaceHandler extends NamespaceHandlerSupport {
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.xml.NamespaceHandler#init()
*/
public void init() {
registerBeanDefinitionParser("mapping-converter", new MappingMongoConverterParser());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2019 the original author or authors.
* Copyright 2011-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,9 +22,12 @@ import java.util.Map;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionValidationException;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.data.mongodb.core.MongoClientOptionsFactoryBean;
import org.springframework.data.mongodb.core.MongoClientSettingsFactoryBean;
import org.springframework.data.mongodb.core.MongoServerApiFactoryBean;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
@@ -35,66 +38,99 @@ import org.w3c.dom.Element;
* @author Oliver Gierke
* @author Thomas Darimont
* @author Christoph Strobl
* @author Mark Paluch
*/
@SuppressWarnings("deprecation")
abstract class MongoParsingUtils {
private MongoParsingUtils() {}
/**
* Parses the mongo replica-set element.
*
* @param parserContext the parser context
* @param element the mongo element
* @param mongoBuilder the bean definition builder to populate
* @return
*/
static void parseReplicaSet(Element element, BeanDefinitionBuilder mongoBuilder) {
setPropertyValue(mongoBuilder, element, "replica-set", "replicaSetSeeds");
}
/**
* Parses the {@code mongo:client-options} sub-element. Populates the given attribute factory with the proper
* Parses the {@code mongo:client-settings} sub-element. Populates the given attribute factory with the proper
* attributes.
*
* @param element must not be {@literal null}.
* @param mongoClientBuilder must not be {@literal null}.
* @param element
* @param mongoClientBuilder
* @return
* @since 1.7
* @since 3.0
*/
public static boolean parseMongoClientOptions(Element element, BeanDefinitionBuilder mongoClientBuilder) {
public static boolean parseMongoClientSettings(Element element, BeanDefinitionBuilder mongoClientBuilder) {
Element optionsElement = DomUtils.getChildElementByTagName(element, "client-options");
if (optionsElement == null) {
Element settingsElement = DomUtils.getChildElementByTagName(element, "client-settings");
if (settingsElement == null) {
return false;
}
BeanDefinitionBuilder clientOptionsDefBuilder = BeanDefinitionBuilder
.genericBeanDefinition(MongoClientOptionsFactoryBean.class);
.genericBeanDefinition(MongoClientSettingsFactoryBean.class);
setPropertyValue(clientOptionsDefBuilder, optionsElement, "description", "description");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "min-connections-per-host", "minConnectionsPerHost");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "connections-per-host", "connectionsPerHost");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "threads-allowed-to-block-for-connection-multiplier",
"threadsAllowedToBlockForConnectionMultiplier");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "max-wait-time", "maxWaitTime");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "max-connection-idle-time", "maxConnectionIdleTime");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "max-connection-life-time", "maxConnectionLifeTime");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "connect-timeout", "connectTimeout");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "socket-timeout", "socketTimeout");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "socket-keep-alive", "socketKeepAlive");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "read-preference", "readPreference");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "write-concern", "writeConcern");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "heartbeat-frequency", "heartbeatFrequency");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "min-heartbeat-frequency", "minHeartbeatFrequency");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "heartbeat-connect-timeout", "heartbeatConnectTimeout");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "heartbeat-socket-timeout", "heartbeatSocketTimeout");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "ssl", "ssl");
setPropertyReference(clientOptionsDefBuilder, optionsElement, "ssl-socket-factory-ref", "sslSocketFactory");
setPropertyValue(clientOptionsDefBuilder, optionsElement, "server-selection-timeout", "serverSelectionTimeout");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "application-name", "applicationName");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "read-preference", "readPreference");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "read-concern", "readConcern");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "write-concern", "writeConcern");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "retry-reads", "retryReads");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "retry-writes", "retryWrites");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "uuid-representation", "uUidRepresentation");
mongoClientBuilder.addPropertyValue("mongoClientOptions", clientOptionsDefBuilder.getBeanDefinition());
// SocketSettings
setPropertyValue(clientOptionsDefBuilder, settingsElement, "socket-connect-timeout", "socketConnectTimeoutMS");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "socket-read-timeout", "socketReadTimeoutMS");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "socket-receive-buffer-size", "socketReceiveBufferSize");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "socket-send-buffer-size", "socketSendBufferSize");
// Server Settings
setPropertyValue(clientOptionsDefBuilder, settingsElement, "server-heartbeat-frequency",
"serverHeartbeatFrequencyMS");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "server-min-heartbeat-frequency",
"serverMinHeartbeatFrequencyMS");
// Cluster Settings
setPropertyValue(clientOptionsDefBuilder, settingsElement, "cluster-srv-host", "clusterSrvHost");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "cluster-hosts", "clusterHosts");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "cluster-connection-mode", "clusterConnectionMode");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "cluster-type", "custerRequiredClusterType");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "cluster-local-threshold", "clusterLocalThresholdMS");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "cluster-server-selection-timeout",
"clusterServerSelectionTimeoutMS");
// Connection Pool Settings
setPropertyValue(clientOptionsDefBuilder, settingsElement, "connection-pool-max-size", "poolMaxSize");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "connection-pool-min-size", "poolMinSize");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "connection-pool-max-wait-time", "poolMaxWaitTimeMS");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "connection-pool-max-connection-life-time",
"poolMaxConnectionLifeTimeMS");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "connection-pool-max-connection-idle-time",
"poolMaxConnectionIdleTimeMS");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "connection-pool-maintenance-initial-delay",
"poolMaintenanceInitialDelayMS");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "connection-pool-maintenance-frequency",
"poolMaintenanceFrequencyMS");
// SSL Settings
setPropertyValue(clientOptionsDefBuilder, settingsElement, "ssl-enabled", "sslEnabled");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "ssl-invalid-host-name-allowed",
"sslInvalidHostNameAllowed");
setPropertyValue(clientOptionsDefBuilder, settingsElement, "ssl-provider", "sslProvider");
// Field level encryption
setPropertyReference(clientOptionsDefBuilder, settingsElement, "encryption-settings-ref", "autoEncryptionSettings");
// ServerAPI
if (StringUtils.hasText(settingsElement.getAttribute("server-api-version"))) {
MongoServerApiFactoryBean serverApiFactoryBean = new MongoServerApiFactoryBean();
serverApiFactoryBean.setVersion(settingsElement.getAttribute("server-api-version"));
try {
clientOptionsDefBuilder.addPropertyValue("serverApi", serverApiFactoryBean.getObject());
} catch (Exception exception) {
throw new BeanDefinitionValidationException("Non parsable server-api.", exception);
}
} else {
setPropertyReference(clientOptionsDefBuilder, settingsElement, "server-api-ref", "serverApi");
}
// and the rest
mongoClientBuilder.addPropertyValue("mongoClientSettings", clientOptionsDefBuilder.getBeanDefinition());
return true;
}
@@ -116,6 +152,24 @@ abstract class MongoParsingUtils {
return builder;
}
/**
* Returns the {@link BeanDefinitionBuilder} to build a {@link BeanDefinition} for a
* {@link ReadConcernPropertyEditor}.
*
* @return
* @since 3.0
*/
static BeanDefinitionBuilder getReadConcernPropertyEditorBuilder() {
Map<String, Class<?>> customEditors = new ManagedMap<>();
customEditors.put("com.mongodb.ReadConcern", ReadConcernPropertyEditor.class);
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class);
builder.addPropertyValue("customEditors", customEditors);
return builder;
}
/**
* One should only register one bean definition but want to have the convenience of using
* AbstractSingleBeanDefinitionParser but have the side effect of registering a 'default' property editor with the
@@ -123,7 +177,7 @@ abstract class MongoParsingUtils {
*/
static BeanDefinitionBuilder getServerAddressPropertyEditorBuilder() {
Map<String, String> customEditors = new ManagedMap<String, String>();
Map<String, String> customEditors = new ManagedMap<>();
customEditors.put("com.mongodb.ServerAddress[]",
"org.springframework.data.mongodb.config.ServerAddressPropertyEditor");
@@ -141,7 +195,7 @@ abstract class MongoParsingUtils {
*/
static BeanDefinitionBuilder getReadPreferencePropertyEditorBuilder() {
Map<String, Class<?>> customEditors = new ManagedMap<String, Class<?>>();
Map<String, Class<?>> customEditors = new ManagedMap<>();
customEditors.put("com.mongodb.ReadPreference", ReadPreferencePropertyEditor.class);
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class);
@@ -167,4 +221,41 @@ abstract class MongoParsingUtils {
return builder;
}
/**
* Returns the {@link BeanDefinitionBuilder} to build a {@link BeanDefinition} for a
* {@link ConnectionStringPropertyEditor}.
*
* @return
* @since 3.0
*/
static BeanDefinitionBuilder getConnectionStringPropertyEditorBuilder() {
Map<String, Class<?>> customEditors = new ManagedMap<>();
customEditors.put("com.mongodb.ConnectionString", ConnectionStringPropertyEditor.class);
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class);
builder.addPropertyValue("customEditors", customEditors);
return builder;
}
/**
* Returns the {@link BeanDefinitionBuilder} to build a {@link BeanDefinition} for a
* {@link ConnectionStringPropertyEditor}.
*
* @return
* @since 3.0
*/
static BeanDefinitionBuilder getUUidRepresentationEditorBuilder() {
Map<String, Class<?>> customEditors = new ManagedMap<>();
customEditors.put("org.bson.UuidRepresentation", UUidRepresentationPropertyEditor.class);
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class);
builder.addPropertyValue("customEditors", customEditors);
return builder;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2019 the original author or authors.
* Copyright 2011-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,10 +39,6 @@ import org.w3c.dom.Element;
*/
class MongoTemplateParser extends AbstractBeanDefinitionParser {
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.xml.AbstractBeanDefinitionParser#resolveId(org.w3c.dom.Element, org.springframework.beans.factory.support.AbstractBeanDefinition, org.springframework.beans.factory.xml.ParserContext)
*/
@Override
protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext)
throws BeanDefinitionStoreException {
@@ -51,10 +47,6 @@ class MongoTemplateParser extends AbstractBeanDefinitionParser {
return StringUtils.hasText(id) ? id : BeanNames.MONGO_TEMPLATE_BEAN_NAME;
}
/*
* (non-Javadoc)
* @see org.springframework.beans.factory.xml.AbstractBeanDefinitionParser#parseInternal(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext)
*/
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {

View File

@@ -0,0 +1,53 @@
/*
* Copyright 2020-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.config;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.data.mapping.context.PersistentEntities;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
/**
* Simple helper to be able to wire the {@link PersistentEntities} from a {@link MappingMongoConverter} bean available
* in the application context.
*
* @author Oliver Gierke
* @author Mark Paluch
* @author Christoph Strobl
* @since 3.1
*/
public class PersistentEntitiesFactoryBean implements FactoryBean<PersistentEntities> {
private final MappingMongoConverter converter;
/**
* Creates a new {@link PersistentEntitiesFactoryBean} for the given {@link MappingMongoConverter}.
*
* @param converter must not be {@literal null}.
*/
public PersistentEntitiesFactoryBean(MappingMongoConverter converter) {
this.converter = converter;
}
@Override
public PersistentEntities getObject() {
return PersistentEntities.of(converter.getMappingContext());
}
@Override
public Class<?> getObjectType() {
return PersistentEntities.class;
}
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright 2020-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.config;
import java.lang.annotation.Annotation;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.data.auditing.ReactiveIsNewAwareAuditingHandler;
import org.springframework.data.auditing.config.AuditingBeanDefinitionRegistrarSupport;
import org.springframework.data.auditing.config.AuditingConfiguration;
import org.springframework.data.config.ParsingUtils;
import org.springframework.data.mongodb.core.mapping.event.ReactiveAuditingEntityCallback;
import org.springframework.util.Assert;
/**
* {@link ImportBeanDefinitionRegistrar} to enable {@link EnableReactiveMongoAuditing} annotation.
*
* @author Mark Paluch
* @author Christoph Strobl
* @since 3.1
*/
class ReactiveMongoAuditingRegistrar extends AuditingBeanDefinitionRegistrarSupport {
@Override
protected Class<? extends Annotation> getAnnotation() {
return EnableReactiveMongoAuditing.class;
}
@Override
protected String getAuditingHandlerBeanName() {
return "reactiveMongoAuditingHandler";
}
@Override
protected void postProcess(BeanDefinitionBuilder builder, AuditingConfiguration configuration,
BeanDefinitionRegistry registry) {
builder.setFactoryMethod("from").addConstructorArgReference("mongoMappingContext");
}
@Override
protected BeanDefinitionBuilder getAuditHandlerBeanDefinitionBuilder(AuditingConfiguration configuration) {
Assert.notNull(configuration, "AuditingConfiguration must not be null");
return configureDefaultAuditHandlerAttributes(configuration,
BeanDefinitionBuilder.rootBeanDefinition(ReactiveIsNewAwareAuditingHandler.class));
}
@Override
protected void registerAuditListenerBeanDefinition(BeanDefinition auditingHandlerDefinition,
BeanDefinitionRegistry registry) {
Assert.notNull(auditingHandlerDefinition, "BeanDefinition must not be null");
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ReactiveAuditingEntityCallback.class);
builder.addConstructorArgValue(ParsingUtils.getObjectFactoryBeanDefinition(getAuditingHandlerBeanName(), registry));
builder.getRawBeanDefinition().setSource(auditingHandlerDefinition.getSource());
registerInfrastructureBeanWithId(builder.getBeanDefinition(), ReactiveAuditingEntityCallback.class.getName(),
registry);
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2019-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.config;
import java.beans.PropertyEditorSupport;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import com.mongodb.ReadConcern;
import com.mongodb.ReadConcernLevel;
/**
* Parse a {@link String} to a {@link ReadConcern}. If it is a well know {@link String} as identified by the
* {@link ReadConcernLevel#fromString(String)}.
*
* @author Christoph Strobl
* @since 3.0
*/
public class ReadConcernPropertyEditor extends PropertyEditorSupport {
@Override
public void setAsText(@Nullable String readConcernString) {
if (!StringUtils.hasText(readConcernString)) {
return;
}
setValue(new ReadConcern(ReadConcernLevel.fromString(readConcernString)));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2019 the original author or authors.
* Copyright 2015-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,10 +29,6 @@ import com.mongodb.ReadPreference;
*/
public class ReadPreferencePropertyEditor extends PropertyEditorSupport {
/*
* (non-Javadoc)
* @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
*/
@Override
public void setAsText(@Nullable String readPreferenceString) throws IllegalArgumentException {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2019 the original author or authors.
* Copyright 2011-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,8 +21,8 @@ import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@@ -43,13 +43,9 @@ public class ServerAddressPropertyEditor extends PropertyEditorSupport {
* A port is a number without a leading 0 at the end of the address that is proceeded by just a single :.
*/
private static final String HOST_PORT_SPLIT_PATTERN = "(?<!:):(?=[123456789]\\d*$)";
private static final String COULD_NOT_PARSE_ADDRESS_MESSAGE = "Could not parse address {} '{}'. Check your replica set configuration!";
private static final Logger LOG = LoggerFactory.getLogger(ServerAddressPropertyEditor.class);
private static final String COULD_NOT_PARSE_ADDRESS_MESSAGE = "Could not parse address %s '%s'; Check your replica set configuration";
private static final Log LOG = LogFactory.getLog(ServerAddressPropertyEditor.class);
/*
* (non-Javadoc)
* @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
*/
@Override
public void setAsText(@Nullable String replicaSetString) {
@@ -72,7 +68,7 @@ public class ServerAddressPropertyEditor extends PropertyEditorSupport {
if (serverAddresses.isEmpty()) {
throw new IllegalArgumentException(
"Could not resolve at least one server of the replica set configuration! Validate your config!");
"Could not resolve at least one server of the replica set configuration; Validate your config");
}
setValue(serverAddresses.toArray(new ServerAddress[serverAddresses.size()]));
@@ -88,14 +84,18 @@ public class ServerAddressPropertyEditor extends PropertyEditorSupport {
private ServerAddress parseServerAddress(String source) {
if (!StringUtils.hasText(source)) {
LOG.warn(COULD_NOT_PARSE_ADDRESS_MESSAGE, "source", source);
if(LOG.isWarnEnabled()) {
LOG.warn(String.format(COULD_NOT_PARSE_ADDRESS_MESSAGE, "source", source));
}
return null;
}
String[] hostAndPort = extractHostAddressAndPort(source.trim());
if (hostAndPort.length > 2) {
LOG.warn(COULD_NOT_PARSE_ADDRESS_MESSAGE, "source", source);
if(LOG.isWarnEnabled()) {
LOG.warn(String.format(COULD_NOT_PARSE_ADDRESS_MESSAGE, "source", source));
}
return null;
}
@@ -105,9 +105,13 @@ public class ServerAddressPropertyEditor extends PropertyEditorSupport {
return port == null ? new ServerAddress(hostAddress) : new ServerAddress(hostAddress, port);
} catch (UnknownHostException e) {
LOG.warn(COULD_NOT_PARSE_ADDRESS_MESSAGE, "host", hostAndPort[0]);
if(LOG.isWarnEnabled()) {
LOG.warn(String.format(COULD_NOT_PARSE_ADDRESS_MESSAGE, "host", hostAndPort[0]));
}
} catch (NumberFormatException e) {
LOG.warn(COULD_NOT_PARSE_ADDRESS_MESSAGE, "port", hostAndPort[1]);
if(LOG.isWarnEnabled()) {
LOG.warn(String.format(COULD_NOT_PARSE_ADDRESS_MESSAGE, "port", hostAndPort[1]));
}
}
return null;
@@ -121,7 +125,7 @@ public class ServerAddressPropertyEditor extends PropertyEditorSupport {
*/
private String[] extractHostAddressAndPort(String addressAndPortSource) {
Assert.notNull(addressAndPortSource, "Address and port source must not be null!");
Assert.notNull(addressAndPortSource, "Address and port source must not be null");
String[] hostAndPort = addressAndPortSource.split(HOST_PORT_SPLIT_PATTERN);
String hostAddress = hostAndPort[0];

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,10 +26,6 @@ import com.mongodb.WriteConcern;
*/
public class StringToWriteConcernConverter implements Converter<String, WriteConcern> {
/*
* (non-Javadoc)
* @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object)
*/
public WriteConcern convert(String source) {
WriteConcern writeConcern = WriteConcern.valueOf(source);

View File

@@ -0,0 +1,41 @@
/*
* Copyright 2020-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.config;
import java.beans.PropertyEditorSupport;
import org.bson.UuidRepresentation;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
/**
* Parse a {@link String} to a {@link UuidRepresentation}.
*
* @author Christoph Strobl
* @since 3.0
*/
public class UUidRepresentationPropertyEditor extends PropertyEditorSupport {
@Override
public void setAsText(@Nullable String value) {
if (!StringUtils.hasText(value)) {
return;
}
setValue(UuidRepresentation.valueOf(value));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2019 the original author or authors.
* Copyright 2011-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,7 +34,7 @@ import com.mongodb.WriteConcern;
public class WriteConcernPropertyEditor extends PropertyEditorSupport {
/**
* Parse a string to a List<ServerAddress>
* Parse a string to a {@link WriteConcern}.
*/
@Override
public void setAsText(@Nullable String writeConcernString) {
@@ -51,6 +51,5 @@ public class WriteConcernPropertyEditor extends PropertyEditorSupport {
// pass on the string to the constructor
setValue(new WriteConcern(writeConcernString));
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018-2019 the original author or authors.
* Copyright 2018-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,10 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.AllArgsConstructor;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@@ -26,20 +22,16 @@ import java.util.stream.Collectors;
import org.bson.Document;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext;
import org.springframework.data.mongodb.core.aggregation.AggregationOptions;
import org.springframework.data.mongodb.core.aggregation.CountOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationOptions.DomainTypeMapping;
import org.springframework.data.mongodb.core.aggregation.RelaxedTypeBasedAggregationOperationContext;
import org.springframework.data.mongodb.core.aggregation.TypeBasedAggregationOperationContext;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.convert.QueryMapper;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.util.Lazy;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* Utility methods to map {@link org.springframework.data.mongodb.core.aggregation.Aggregation} pipeline definitions and
@@ -49,34 +41,50 @@ import org.springframework.util.ObjectUtils;
* @author Mark Paluch
* @since 2.1
*/
@AllArgsConstructor
class AggregationUtil {
QueryMapper queryMapper;
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext;
Lazy<AggregationOperationContext> untypedMappingContext;
/**
* Prepare the {@link AggregationOperationContext} for a given aggregation by either returning the context itself it
* is not {@literal null}, create a {@link TypeBasedAggregationOperationContext} if the aggregation contains type
* information (is a {@link TypedAggregation}) or use the {@link Aggregation#DEFAULT_CONTEXT}.
*
* @param aggregation must not be {@literal null}.
* @param context can be {@literal null}.
* @return the root {@link AggregationOperationContext} to use.
*/
AggregationOperationContext prepareAggregationContext(Aggregation aggregation,
@Nullable AggregationOperationContext context) {
AggregationUtil(QueryMapper queryMapper,
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext) {
if (context != null) {
return context;
this.queryMapper = queryMapper;
this.mappingContext = mappingContext;
this.untypedMappingContext = Lazy
.of(() -> new RelaxedTypeBasedAggregationOperationContext(Object.class, mappingContext, queryMapper));
}
AggregationOperationContext createAggregationContext(Aggregation aggregation, @Nullable Class<?> inputType) {
DomainTypeMapping domainTypeMapping = aggregation.getOptions().getDomainTypeMapping();
if (domainTypeMapping == DomainTypeMapping.NONE) {
return Aggregation.DEFAULT_CONTEXT;
}
if (aggregation instanceof TypedAggregation) {
return new TypeBasedAggregationOperationContext(((TypedAggregation) aggregation).getInputType(), mappingContext,
queryMapper);
if (!(aggregation instanceof TypedAggregation)) {
if(inputType == null) {
return untypedMappingContext.get();
}
if (domainTypeMapping == DomainTypeMapping.STRICT
&& !aggregation.getPipeline().containsUnionWith()) {
return new TypeBasedAggregationOperationContext(inputType, mappingContext, queryMapper);
}
return new RelaxedTypeBasedAggregationOperationContext(inputType, mappingContext, queryMapper);
}
return Aggregation.DEFAULT_CONTEXT;
inputType = ((TypedAggregation<?>) aggregation).getInputType();
if (domainTypeMapping == DomainTypeMapping.STRICT
&& !aggregation.getPipeline().containsUnionWith()) {
return new TypeBasedAggregationOperationContext(inputType, mappingContext, queryMapper);
}
return new RelaxedTypeBasedAggregationOperationContext(inputType, mappingContext, queryMapper);
}
/**
@@ -87,12 +95,7 @@ class AggregationUtil {
* @return
*/
List<Document> createPipeline(Aggregation aggregation, AggregationOperationContext context) {
if (!ObjectUtils.nullSafeEquals(context, Aggregation.DEFAULT_CONTEXT)) {
return aggregation.toPipeline(context);
}
return mapAggregationPipeline(aggregation.toPipeline(context));
return aggregation.toPipeline(context);
}
/**
@@ -103,63 +106,7 @@ class AggregationUtil {
* @return
*/
Document createCommand(String collection, Aggregation aggregation, AggregationOperationContext context) {
Document command = aggregation.toDocument(collection, context);
if (!ObjectUtils.nullSafeEquals(context, Aggregation.DEFAULT_CONTEXT)) {
return command;
}
command.put("pipeline", mapAggregationPipeline(command.get("pipeline", List.class)));
return command;
}
/**
* Create a {@code $count} aggregation for {@link Query} and optionally a {@link Class entity class}.
*
* @param query must not be {@literal null}.
* @param entityClass can be {@literal null} if the {@link Query} object is empty.
* @return the {@link Aggregation} pipeline definition to run a {@code $count} aggregation.
*/
Aggregation createCountAggregation(Query query, @Nullable Class<?> entityClass) {
List<AggregationOperation> pipeline = computeCountAggregationPipeline(query, entityClass);
Aggregation aggregation = entityClass != null ? Aggregation.newAggregation(entityClass, pipeline)
: Aggregation.newAggregation(pipeline);
aggregation.withOptions(AggregationOptions.builder().collation(query.getCollation().orElse(null)).build());
return aggregation;
}
private List<AggregationOperation> computeCountAggregationPipeline(Query query, @Nullable Class<?> entityType) {
CountOperation count = Aggregation.count().as("totalEntityCount");
if (query.getQueryObject().isEmpty()) {
return Collections.singletonList(count);
}
Assert.notNull(entityType, "Entity type must not be null!");
Document mappedQuery = queryMapper.getMappedObject(query.getQueryObject(),
mappingContext.getPersistentEntity(entityType));
CriteriaDefinition criteria = new CriteriaDefinition() {
@Override
public Document getCriteriaObject() {
return mappedQuery;
}
@Nullable
@Override
public String getKey() {
return null;
}
};
return Arrays.asList(Aggregation.match(criteria), count);
return aggregation.toDocument(collection, context);
}
private List<Document> mapAggregationPipeline(List<Document> pipeline) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2019 the original author or authors.
* Copyright 2015-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,10 +24,14 @@ import org.springframework.data.util.Pair;
import com.mongodb.bulk.BulkWriteResult;
/**
* Bulk operations for insert/update/remove actions on a collection. These bulks operation are available since MongoDB
* 2.6 and make use of low level bulk commands on the protocol level. This interface defines a fluent API to add
* multiple single operations or list of similar operations in sequence which can then eventually be executed by calling
* Bulk operations for insert/update/remove actions on a collection. Bulk operations are available since MongoDB 2.6 and
* make use of low level bulk commands on the protocol level. This interface defines a fluent API to add multiple single
* operations or list of similar operations in sequence which can then eventually be executed by calling
* {@link #execute()}.
* <p>
* Bulk operations are issued as one batch that pulls together all insert, update, and delete operations. Operations
* that require individual operation results such as optimistic locking (using {@code @Version}) are not supported and
* the version field remains not populated.
*
* @author Tobias Trelle
* @author Oliver Gierke
@@ -94,7 +98,6 @@ public interface BulkOperations {
* Add a list of updates to the bulk operation. For each update request, all matching documents are updated.
*
* @param updates Update operations to perform.
* @return The bulk operation.
* @return the current {@link BulkOperations} instance with the update added, will never be {@literal null}.
*/
BulkOperations updateMulti(List<Pair<Query, Update>> updates);
@@ -105,7 +108,6 @@ public interface BulkOperations {
*
* @param query Update criteria.
* @param update Update operation to perform.
* @return The bulk operation.
* @return the current {@link BulkOperations} instance with the update added, will never be {@literal null}.
*/
BulkOperations upsert(Query query, Update update);
@@ -115,7 +117,6 @@ public interface BulkOperations {
* else an insert.
*
* @param updates Updates/insert operations to perform.
* @return The bulk operation.
* @return the current {@link BulkOperations} instance with the update added, will never be {@literal null}.
*/
BulkOperations upsert(List<Pair<Query, Update>> updates);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018-2019 the original author or authors.
* Copyright 2018-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,8 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.EqualsAndHashCode;
import java.time.Instant;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
@@ -27,6 +25,7 @@ import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.messaging.Message;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import com.mongodb.client.model.changestream.ChangeStreamDocument;
import com.mongodb.client.model.changestream.OperationType;
@@ -37,22 +36,29 @@ import com.mongodb.client.model.changestream.OperationType;
*
* @author Christoph Strobl
* @author Mark Paluch
* @author Myroslav Kosinskyi
* @since 2.1
*/
@EqualsAndHashCode
public class ChangeStreamEvent<T> {
@SuppressWarnings("rawtypes") //
private static final AtomicReferenceFieldUpdater<ChangeStreamEvent, Object> CONVERTED_UPDATER = AtomicReferenceFieldUpdater
.newUpdater(ChangeStreamEvent.class, Object.class, "converted");
private static final AtomicReferenceFieldUpdater<ChangeStreamEvent, Object> CONVERTED_FULL_DOCUMENT_UPDATER = AtomicReferenceFieldUpdater
.newUpdater(ChangeStreamEvent.class, Object.class, "convertedFullDocument");
@SuppressWarnings("rawtypes") //
private static final AtomicReferenceFieldUpdater<ChangeStreamEvent, Object> CONVERTED_FULL_DOCUMENT_BEFORE_CHANGE_UPDATER = AtomicReferenceFieldUpdater
.newUpdater(ChangeStreamEvent.class, Object.class, "convertedFullDocumentBeforeChange");
private final @Nullable ChangeStreamDocument<Document> raw;
private final Class<T> targetType;
private final MongoConverter converter;
// accessed through CONVERTED_UPDATER.
private volatile @Nullable T converted;
// accessed through CONVERTED_FULL_DOCUMENT_UPDATER.
private volatile @Nullable T convertedFullDocument;
// accessed through CONVERTED_FULL_DOCUMENT_BEFORE_CHANGE_UPDATER.
private volatile @Nullable T convertedFullDocumentBeforeChange;
/**
* @param raw can be {@literal null}.
@@ -149,27 +155,43 @@ public class ChangeStreamEvent<T> {
@Nullable
public T getBody() {
if (raw == null) {
if (raw == null || raw.getFullDocument() == null) {
return null;
}
Document fullDocument = raw.getFullDocument();
return getConvertedFullDocument(raw.getFullDocument());
}
if (fullDocument == null) {
return targetType.cast(fullDocument);
/**
* Get the potentially converted {@link ChangeStreamDocument#getFullDocumentBeforeChange() document} before being changed.
*
* @return {@literal null} when {@link #getRaw()} or {@link ChangeStreamDocument#getFullDocumentBeforeChange()} is
* {@literal null}.
* @since 4.0
*/
@Nullable
public T getBodyBeforeChange() {
if (raw == null || raw.getFullDocumentBeforeChange() == null) {
return null;
}
return getConverted(fullDocument);
return getConvertedFullDocumentBeforeChange(raw.getFullDocumentBeforeChange());
}
@SuppressWarnings("unchecked")
private T getConverted(Document fullDocument) {
return (T) doGetConverted(fullDocument);
private T getConvertedFullDocumentBeforeChange(Document fullDocument) {
return (T) doGetConverted(fullDocument, CONVERTED_FULL_DOCUMENT_BEFORE_CHANGE_UPDATER);
}
private Object doGetConverted(Document fullDocument) {
@SuppressWarnings("unchecked")
private T getConvertedFullDocument(Document fullDocument) {
return (T) doGetConverted(fullDocument, CONVERTED_FULL_DOCUMENT_UPDATER);
}
Object result = CONVERTED_UPDATER.get(this);
private Object doGetConverted(Document fullDocument, AtomicReferenceFieldUpdater<ChangeStreamEvent, Object> updater) {
Object result = updater.get(this);
if (result != null) {
return result;
@@ -178,25 +200,44 @@ public class ChangeStreamEvent<T> {
if (ClassUtils.isAssignable(Document.class, fullDocument.getClass())) {
result = converter.read(targetType, fullDocument);
return CONVERTED_UPDATER.compareAndSet(this, null, result) ? result : CONVERTED_UPDATER.get(this);
return updater.compareAndSet(this, null, result) ? result : updater.get(this);
}
if (converter.getConversionService().canConvert(fullDocument.getClass(), targetType)) {
result = converter.getConversionService().convert(fullDocument, targetType);
return CONVERTED_UPDATER.compareAndSet(this, null, result) ? result : CONVERTED_UPDATER.get(this);
return updater.compareAndSet(this, null, result) ? result : updater.get(this);
}
throw new IllegalArgumentException(String.format("No converter found capable of converting %s to %s",
fullDocument.getClass(), targetType));
throw new IllegalArgumentException(
String.format("No converter found capable of converting %s to %s", fullDocument.getClass(), targetType));
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "ChangeStreamEvent {" + "raw=" + raw + ", targetType=" + targetType + '}';
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ChangeStreamEvent<?> that = (ChangeStreamEvent<?>) o;
if (!ObjectUtils.nullSafeEquals(this.raw, that.raw)) {
return false;
}
return ObjectUtils.nullSafeEquals(this.targetType, that.targetType);
}
@Override
public int hashCode() {
int result = raw != null ? raw.hashCode() : 0;
result = 31 * result + ObjectUtils.nullSafeHashCode(targetType);
return result;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018-2019 the original author or authors.
* Copyright 2018-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,8 +15,6 @@
*/
package org.springframework.data.mongodb.core;
import lombok.EqualsAndHashCode;
import java.time.Instant;
import java.util.Arrays;
import java.util.Optional;
@@ -25,7 +23,6 @@ import org.bson.BsonDocument;
import org.bson.BsonTimestamp;
import org.bson.BsonValue;
import org.bson.Document;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Collation;
import org.springframework.lang.Nullable;
@@ -35,6 +32,7 @@ import org.springframework.util.ObjectUtils;
import com.mongodb.client.model.changestream.ChangeStreamDocument;
import com.mongodb.client.model.changestream.FullDocument;
import com.mongodb.client.model.changestream.FullDocumentBeforeChange;
/**
* Options applicable to MongoDB <a href="https://docs.mongodb.com/manual/changeStreams/">Change Streams</a>. Intended
@@ -43,14 +41,15 @@ import com.mongodb.client.model.changestream.FullDocument;
*
* @author Christoph Strobl
* @author Mark Paluch
* @author Myroslav Kosinskyi
* @since 2.1
*/
@EqualsAndHashCode
public class ChangeStreamOptions {
private @Nullable Object filter;
private @Nullable BsonValue resumeToken;
private @Nullable FullDocument fullDocumentLookup;
private @Nullable FullDocumentBeforeChange fullDocumentBeforeChangeLookup;
private @Nullable Collation collation;
private @Nullable Object resumeTimestamp;
private Resume resume = Resume.UNDEFINED;
@@ -78,6 +77,14 @@ public class ChangeStreamOptions {
return Optional.ofNullable(fullDocumentLookup);
}
/**
* @return {@link Optional#empty()} if not set.
* @since 4.0
*/
public Optional<FullDocumentBeforeChange> getFullDocumentBeforeChangeLookup() {
return Optional.ofNullable(fullDocumentBeforeChangeLookup);
}
/**
* @return {@link Optional#empty()} if not set.
*/
@@ -152,10 +159,52 @@ public class ChangeStreamOptions {
}
throw new IllegalArgumentException(
"o_O that should actually not happen. The timestamp should be an Instant or a BsonTimestamp but was "
"o_O that should actually not happen; The timestamp should be an Instant or a BsonTimestamp but was "
+ ObjectUtils.nullSafeClassName(timestamp));
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ChangeStreamOptions that = (ChangeStreamOptions) o;
if (!ObjectUtils.nullSafeEquals(this.filter, that.filter)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(this.resumeToken, that.resumeToken)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(this.fullDocumentLookup, that.fullDocumentLookup)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(this.fullDocumentBeforeChangeLookup, that.fullDocumentBeforeChangeLookup)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(this.collation, that.collation)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(this.resumeTimestamp, that.resumeTimestamp)) {
return false;
}
return resume == that.resume;
}
@Override
public int hashCode() {
int result = ObjectUtils.nullSafeHashCode(filter);
result = 31 * result + ObjectUtils.nullSafeHashCode(resumeToken);
result = 31 * result + ObjectUtils.nullSafeHashCode(fullDocumentLookup);
result = 31 * result + ObjectUtils.nullSafeHashCode(fullDocumentBeforeChangeLookup);
result = 31 * result + ObjectUtils.nullSafeHashCode(collation);
result = 31 * result + ObjectUtils.nullSafeHashCode(resumeTimestamp);
result = 31 * result + ObjectUtils.nullSafeHashCode(resume);
return result;
}
/**
* @author Christoph Strobl
* @since 2.2
@@ -186,6 +235,7 @@ public class ChangeStreamOptions {
private @Nullable Object filter;
private @Nullable BsonValue resumeToken;
private @Nullable FullDocument fullDocumentLookup;
private @Nullable FullDocumentBeforeChange fullDocumentBeforeChangeLookup;
private @Nullable Collation collation;
private @Nullable Object resumeTimestamp;
private Resume resume = Resume.UNDEFINED;
@@ -200,7 +250,7 @@ public class ChangeStreamOptions {
*/
public ChangeStreamOptionsBuilder collation(Collation collation) {
Assert.notNull(collation, "Collation must not be null nor empty!");
Assert.notNull(collation, "Collation must not be null nor empty");
this.collation = collation;
return this;
@@ -208,13 +258,13 @@ public class ChangeStreamOptions {
/**
* Set the filter to apply.
* <p/>
* <br />
* Fields on aggregation expression root level are prefixed to map to fields contained in
* {@link ChangeStreamDocument#getFullDocument() fullDocument}. However {@literal operationType}, {@literal ns},
* {@literal documentKey} and {@literal fullDocument} are reserved words that will be omitted, and therefore taken
* as given, during the mapping procedure. You may want to have a look at the
* <a href="https://docs.mongodb.com/manual/reference/change-events/">structure of Change Events</a>.
* <p/>
* <br />
* Use {@link org.springframework.data.mongodb.core.aggregation.TypedAggregation} to ensure filter expressions are
* mapped to domain type fields.
*
@@ -224,7 +274,7 @@ public class ChangeStreamOptions {
*/
public ChangeStreamOptionsBuilder filter(Aggregation filter) {
Assert.notNull(filter, "Filter must not be null!");
Assert.notNull(filter, "Filter must not be null");
this.filter = filter;
return this;
@@ -253,7 +303,7 @@ public class ChangeStreamOptions {
*/
public ChangeStreamOptionsBuilder resumeToken(BsonValue resumeToken) {
Assert.notNull(resumeToken, "ResumeToken must not be null!");
Assert.notNull(resumeToken, "ResumeToken must not be null");
this.resumeToken = resumeToken;
@@ -282,12 +332,38 @@ public class ChangeStreamOptions {
*/
public ChangeStreamOptionsBuilder fullDocumentLookup(FullDocument lookup) {
Assert.notNull(lookup, "Lookup must not be null!");
Assert.notNull(lookup, "Lookup must not be null");
this.fullDocumentLookup = lookup;
return this;
}
/**
* Set the {@link FullDocumentBeforeChange} lookup to use.
*
* @param lookup must not be {@literal null}.
* @return this.
* @since 4.0
*/
public ChangeStreamOptionsBuilder fullDocumentBeforeChangeLookup(FullDocumentBeforeChange lookup) {
Assert.notNull(lookup, "Lookup must not be null");
this.fullDocumentBeforeChangeLookup = lookup;
return this;
}
/**
* Return the full document before being changed if it is available.
*
* @return this.
* @since 4.0
* @see #fullDocumentBeforeChangeLookup(FullDocumentBeforeChange)
*/
public ChangeStreamOptionsBuilder returnFullDocumentBeforeChange() {
return fullDocumentBeforeChangeLookup(FullDocumentBeforeChange.WHEN_AVAILABLE);
}
/**
* Set the cluster time to resume from.
*
@@ -296,7 +372,7 @@ public class ChangeStreamOptions {
*/
public ChangeStreamOptionsBuilder resumeAt(Instant resumeTimestamp) {
Assert.notNull(resumeTimestamp, "ResumeTimestamp must not be null!");
Assert.notNull(resumeTimestamp, "ResumeTimestamp must not be null");
this.resumeTimestamp = resumeTimestamp;
return this;
@@ -311,7 +387,7 @@ public class ChangeStreamOptions {
*/
public ChangeStreamOptionsBuilder resumeAt(BsonTimestamp resumeTimestamp) {
Assert.notNull(resumeTimestamp, "ResumeTimestamp must not be null!");
Assert.notNull(resumeTimestamp, "ResumeTimestamp must not be null");
this.resumeTimestamp = resumeTimestamp;
return this;
@@ -357,6 +433,7 @@ public class ChangeStreamOptions {
options.filter = this.filter;
options.resumeToken = this.resumeToken;
options.fullDocumentLookup = this.fullDocumentLookup;
options.fullDocumentBeforeChangeLookup = this.fullDocumentBeforeChangeLookup;
options.collation = this.collation;
options.resumeTimestamp = this.resumeTimestamp;
options.resume = this.resume;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2019 the original author or authors.
* Copyright 2010-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,7 +29,7 @@ import com.mongodb.client.MongoCollection;
* @author Grame Rocher
* @author Oliver Gierke
* @author John Brisbin
* @auhtor Christoph Strobl
* @author Christoph Strobl
* @since 1.0
*/
public interface CollectionCallback<T> {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2019 the original author or authors.
* Copyright 2010-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,16 +15,18 @@
*/
package org.springframework.data.mongodb.core;
import lombok.RequiredArgsConstructor;
import java.util.Optional;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.mongodb.core.query.Collation;
import org.springframework.data.mongodb.core.schema.MongoJsonSchema;
import org.springframework.data.mongodb.core.timeseries.Granularity;
import org.springframework.data.mongodb.core.timeseries.GranularityDefinition;
import org.springframework.data.mongodb.core.validation.Validator;
import org.springframework.data.util.Optionals;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import com.mongodb.client.model.ValidationAction;
import com.mongodb.client.model.ValidationLevel;
@@ -44,29 +46,20 @@ public class CollectionOptions {
private @Nullable Boolean capped;
private @Nullable Collation collation;
private ValidationOptions validationOptions;
/**
* Constructs a new <code>CollectionOptions</code> instance.
*
* @param size the collection size in bytes, this data space is preallocated. Can be {@literal null}.
* @param maxDocuments the maximum number of documents in the collection. Can be {@literal null}.
* @param capped true to created a "capped" collection (fixed size with auto-FIFO behavior based on insertion order),
* false otherwise. Can be {@literal null}.
* @deprecated since 2.0 please use {@link CollectionOptions#empty()} as entry point.
*/
@Deprecated
public CollectionOptions(@Nullable Long size, @Nullable Long maxDocuments, @Nullable Boolean capped) {
this(size, maxDocuments, capped, null, ValidationOptions.none());
}
private @Nullable TimeSeriesOptions timeSeriesOptions;
private @Nullable CollectionChangeStreamOptions changeStreamOptions;
private CollectionOptions(@Nullable Long size, @Nullable Long maxDocuments, @Nullable Boolean capped,
@Nullable Collation collation, ValidationOptions validationOptions) {
@Nullable Collation collation, ValidationOptions validationOptions, @Nullable TimeSeriesOptions timeSeriesOptions,
@Nullable CollectionChangeStreamOptions changeStreamOptions) {
this.maxDocuments = maxDocuments;
this.size = size;
this.capped = capped;
this.collation = collation;
this.validationOptions = validationOptions;
this.timeSeriesOptions = timeSeriesOptions;
this.changeStreamOptions = changeStreamOptions;
}
/**
@@ -78,9 +71,9 @@ public class CollectionOptions {
*/
public static CollectionOptions just(Collation collation) {
Assert.notNull(collation, "Collation must not be null!");
Assert.notNull(collation, "Collation must not be null");
return new CollectionOptions(null, null, null, collation, ValidationOptions.none());
return new CollectionOptions(null, null, null, collation, ValidationOptions.none(), null, null);
}
/**
@@ -90,18 +83,45 @@ public class CollectionOptions {
* @since 2.0
*/
public static CollectionOptions empty() {
return new CollectionOptions(null, null, null, null, ValidationOptions.none());
return new CollectionOptions(null, null, null, null, ValidationOptions.none(), null, null);
}
/**
* Quick way to set up {@link CollectionOptions} for a Time Series collection. For more advanced settings use
* {@link #timeSeries(TimeSeriesOptions)}.
*
* @param timeField The name of the property which contains the date in each time series document. Must not be
* {@literal null}.
* @return new instance of {@link CollectionOptions}.
* @see #timeSeries(TimeSeriesOptions)
* @since 3.3
*/
public static CollectionOptions timeSeries(String timeField) {
return empty().timeSeries(TimeSeriesOptions.timeSeries(timeField));
}
/**
* Quick way to set up {@link CollectionOptions} for emitting (pre & post) change events.
*
* @return new instance of {@link CollectionOptions}.
* @see #changeStream(CollectionChangeStreamOptions)
* @see CollectionChangeStreamOptions#preAndPostImages(boolean)
* @since 4.0
*/
public static CollectionOptions emitChangedRevisions() {
return empty().changeStream(CollectionChangeStreamOptions.preAndPostImages(true));
}
/**
* Create new {@link CollectionOptions} with already given settings and capped set to {@literal true}. <br />
* <strong>NOTE</strong> Using capped collections requires defining {@link #size(int)}.
* <strong>NOTE</strong> Using capped collections requires defining {@link #size(long)}.
*
* @return new {@link CollectionOptions}.
* @since 2.0
*/
public CollectionOptions capped() {
return new CollectionOptions(size, maxDocuments, true, collation, validationOptions);
return new CollectionOptions(size, maxDocuments, true, collation, validationOptions, timeSeriesOptions,
changeStreamOptions);
}
/**
@@ -112,7 +132,8 @@ public class CollectionOptions {
* @since 2.0
*/
public CollectionOptions maxDocuments(long maxDocuments) {
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions);
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions, timeSeriesOptions,
changeStreamOptions);
}
/**
@@ -123,7 +144,8 @@ public class CollectionOptions {
* @since 2.0
*/
public CollectionOptions size(long size) {
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions);
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions, timeSeriesOptions,
changeStreamOptions);
}
/**
@@ -134,7 +156,8 @@ public class CollectionOptions {
* @since 2.0
*/
public CollectionOptions collation(@Nullable Collation collation) {
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions);
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions, timeSeriesOptions,
changeStreamOptions);
}
/**
@@ -226,7 +249,7 @@ public class CollectionOptions {
*/
public CollectionOptions schemaValidationLevel(ValidationLevel validationLevel) {
Assert.notNull(validationLevel, "ValidationLevel must not be null!");
Assert.notNull(validationLevel, "ValidationLevel must not be null");
return validation(validationOptions.validationLevel(validationLevel));
}
@@ -240,7 +263,7 @@ public class CollectionOptions {
*/
public CollectionOptions schemaValidationAction(ValidationAction validationAction) {
Assert.notNull(validationAction, "ValidationAction must not be null!");
Assert.notNull(validationAction, "ValidationAction must not be null");
return validation(validationOptions.validationAction(validationAction));
}
@@ -253,8 +276,37 @@ public class CollectionOptions {
*/
public CollectionOptions validation(ValidationOptions validationOptions) {
Assert.notNull(validationOptions, "ValidationOptions must not be null!");
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions);
Assert.notNull(validationOptions, "ValidationOptions must not be null");
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions, timeSeriesOptions,
changeStreamOptions);
}
/**
* Create new {@link CollectionOptions} with the given {@link TimeSeriesOptions}.
*
* @param timeSeriesOptions must not be {@literal null}.
* @return new instance of {@link CollectionOptions}.
* @since 3.3
*/
public CollectionOptions timeSeries(TimeSeriesOptions timeSeriesOptions) {
Assert.notNull(timeSeriesOptions, "TimeSeriesOptions must not be null");
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions, timeSeriesOptions,
changeStreamOptions);
}
/**
* Create new {@link CollectionOptions} with the given {@link TimeSeriesOptions}.
*
* @param changeStreamOptions must not be {@literal null}.
* @return new instance of {@link CollectionOptions}.
* @since 3.3
*/
public CollectionOptions changeStream(CollectionChangeStreamOptions changeStreamOptions) {
Assert.notNull(changeStreamOptions, "ChangeStreamOptions must not be null");
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions, timeSeriesOptions,
changeStreamOptions);
}
/**
@@ -305,6 +357,80 @@ public class CollectionOptions {
return validationOptions.isEmpty() ? Optional.empty() : Optional.of(validationOptions);
}
/**
* Get the {@link TimeSeriesOptions} if available.
*
* @return {@link Optional#empty()} if not specified.
* @since 3.3
*/
public Optional<TimeSeriesOptions> getTimeSeriesOptions() {
return Optional.ofNullable(timeSeriesOptions);
}
/**
* Get the {@link CollectionChangeStreamOptions} if available.
*
* @return {@link Optional#empty()} if not specified.
* @since 4.0
*/
public Optional<CollectionChangeStreamOptions> getChangeStreamOptions() {
return Optional.ofNullable(changeStreamOptions);
}
@Override
public String toString() {
return "CollectionOptions{" + "maxDocuments=" + maxDocuments + ", size=" + size + ", capped=" + capped
+ ", collation=" + collation + ", validationOptions=" + validationOptions + ", timeSeriesOptions="
+ timeSeriesOptions + ", changeStreamOptions=" + changeStreamOptions + ", disableValidation="
+ disableValidation() + ", strictValidation=" + strictValidation() + ", moderateValidation="
+ moderateValidation() + ", warnOnValidationError=" + warnOnValidationError() + ", failOnValidationError="
+ failOnValidationError() + '}';
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CollectionOptions that = (CollectionOptions) o;
if (!ObjectUtils.nullSafeEquals(maxDocuments, that.maxDocuments)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(size, that.size)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(capped, that.capped)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(collation, that.collation)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(validationOptions, that.validationOptions)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(timeSeriesOptions, that.timeSeriesOptions)) {
return false;
}
return ObjectUtils.nullSafeEquals(changeStreamOptions, that.changeStreamOptions);
}
@Override
public int hashCode() {
int result = ObjectUtils.nullSafeHashCode(maxDocuments);
result = 31 * result + ObjectUtils.nullSafeHashCode(size);
result = 31 * result + ObjectUtils.nullSafeHashCode(capped);
result = 31 * result + ObjectUtils.nullSafeHashCode(collation);
result = 31 * result + ObjectUtils.nullSafeHashCode(validationOptions);
result = 31 * result + ObjectUtils.nullSafeHashCode(timeSeriesOptions);
result = 31 * result + ObjectUtils.nullSafeHashCode(changeStreamOptions);
return result;
}
/**
* Encapsulation of ValidationOptions options.
*
@@ -312,7 +438,6 @@ public class CollectionOptions {
* @author Andreas Zink
* @since 2.1
*/
@RequiredArgsConstructor
public static class ValidationOptions {
private static final ValidationOptions NONE = new ValidationOptions(null, null, null);
@@ -321,6 +446,13 @@ public class CollectionOptions {
private final @Nullable ValidationLevel validationLevel;
private final @Nullable ValidationAction validationAction;
public ValidationOptions(Validator validator, ValidationLevel validationLevel, ValidationAction validationAction) {
this.validator = validator;
this.validationLevel = validationLevel;
this.validationAction = validationAction;
}
/**
* Create an empty {@link ValidationOptions}.
*
@@ -381,7 +513,7 @@ public class CollectionOptions {
/**
* Get the {@code validationAction} to perform.
*
* @return @return {@link Optional#empty()} if not set.
* @return {@link Optional#empty()} if not set.
*/
public Optional<ValidationAction> getValidationAction() {
return Optional.ofNullable(validationAction);
@@ -393,5 +525,211 @@ public class CollectionOptions {
boolean isEmpty() {
return !Optionals.isAnyPresent(getValidator(), getValidationAction(), getValidationLevel());
}
@Override
public String toString() {
return "ValidationOptions{" + "validator=" + validator + ", validationLevel=" + validationLevel
+ ", validationAction=" + validationAction + '}';
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ValidationOptions that = (ValidationOptions) o;
if (!ObjectUtils.nullSafeEquals(validator, that.validator)) {
return false;
}
if (validationLevel != that.validationLevel)
return false;
return validationAction == that.validationAction;
}
@Override
public int hashCode() {
int result = ObjectUtils.nullSafeHashCode(validator);
result = 31 * result + ObjectUtils.nullSafeHashCode(validationLevel);
result = 31 * result + ObjectUtils.nullSafeHashCode(validationAction);
return result;
}
}
/**
* Encapsulation of options applied to define collections change stream behaviour.
*
* @author Christoph Strobl
* @since 4.0
*/
public static class CollectionChangeStreamOptions {
private final boolean preAndPostImages;
private CollectionChangeStreamOptions(boolean emitChangedRevisions) {
this.preAndPostImages = emitChangedRevisions;
}
/**
* Output the version of a document before and after changes (the document pre- and post-images).
*
* @return new instance of {@link CollectionChangeStreamOptions}.
*/
public static CollectionChangeStreamOptions preAndPostImages(boolean emitChangedRevisions) {
return new CollectionChangeStreamOptions(true);
}
public boolean getPreAndPostImages() {
return preAndPostImages;
}
@Override
public String toString() {
return "CollectionChangeStreamOptions{" + "preAndPostImages=" + preAndPostImages + '}';
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CollectionChangeStreamOptions that = (CollectionChangeStreamOptions) o;
return preAndPostImages == that.preAndPostImages;
}
@Override
public int hashCode() {
return (preAndPostImages ? 1 : 0);
}
}
/**
* Options applicable to Time Series collections.
*
* @author Christoph Strobl
* @since 3.3
* @see <a href=
* "https://docs.mongodb.com/manual/core/timeseries-collections">https://docs.mongodb.com/manual/core/timeseries-collections</a>
*/
public static class TimeSeriesOptions {
private final String timeField;
private @Nullable final String metaField;
private final GranularityDefinition granularity;
private TimeSeriesOptions(String timeField, @Nullable String metaField, GranularityDefinition granularity) {
Assert.hasText(timeField, "Time field must not be empty or null");
this.timeField = timeField;
this.metaField = metaField;
this.granularity = granularity;
}
/**
* Create a new instance of {@link TimeSeriesOptions} using the given field as its {@literal timeField}. The one,
* that contains the date in each time series document. <br />
* {@link Field#name() Annotated fieldnames} will be considered during the mapping process.
*
* @param timeField must not be {@literal null}.
* @return new instance of {@link TimeSeriesOptions}.
*/
public static TimeSeriesOptions timeSeries(String timeField) {
return new TimeSeriesOptions(timeField, null, Granularity.DEFAULT);
}
/**
* Set the name of the field which contains metadata in each time series document. Should not be the {@literal id}
* nor {@link TimeSeriesOptions#timeSeries(String)} timeField} nor point to an {@literal array} or
* {@link java.util.Collection}. <br />
* {@link Field#name() Annotated fieldnames} will be considered during the mapping process.
*
* @param metaField must not be {@literal null}.
* @return new instance of {@link TimeSeriesOptions}.
*/
public TimeSeriesOptions metaField(String metaField) {
return new TimeSeriesOptions(timeField, metaField, granularity);
}
/**
* Select the {@link GranularityDefinition} parameter to define how data in the time series collection is organized.
* Select one that is closest to the time span between incoming measurements.
*
* @return new instance of {@link TimeSeriesOptions}.
* @see Granularity
*/
public TimeSeriesOptions granularity(GranularityDefinition granularity) {
return new TimeSeriesOptions(timeField, metaField, granularity);
}
/**
* @return never {@literal null}.
*/
public String getTimeField() {
return timeField;
}
/**
* @return can be {@literal null}. Might be an {@literal empty} {@link String} as well, so maybe check via
* {@link org.springframework.util.StringUtils#hasText(String)}.
*/
@Nullable
public String getMetaField() {
return metaField;
}
/**
* @return never {@literal null}.
*/
public GranularityDefinition getGranularity() {
return granularity;
}
@Override
public String toString() {
return "TimeSeriesOptions{" + "timeField='" + timeField + '\'' + ", metaField='" + metaField + '\''
+ ", granularity=" + granularity + '}';
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TimeSeriesOptions that = (TimeSeriesOptions) o;
if (!ObjectUtils.nullSafeEquals(timeField, that.timeField)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(metaField, that.metaField)) {
return false;
}
return ObjectUtils.nullSafeEquals(granularity, that.granularity);
}
@Override
public int hashCode() {
int result = ObjectUtils.nullSafeHashCode(timeField);
result = 31 * result + ObjectUtils.nullSafeHashCode(metaField);
result = 31 * result + ObjectUtils.nullSafeHashCode(granularity);
return result;
}
}
}

View File

@@ -0,0 +1,263 @@
/*
* Copyright 2019-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.bson.Document;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.query.MetricConversion;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
/**
* Value object representing a count query. Count queries using {@code $near} or {@code $nearSphere} require a rewrite
* to {@code $geoWithin}.
*
* @author Christoph Strobl
* @author Mark Paluch
* @since 3.0
*/
class CountQuery {
private final Document source;
private CountQuery(Document source) {
this.source = source;
}
public static CountQuery of(Document source) {
return new CountQuery(source);
}
/**
* Returns the query {@link Document} that can be used with {@code countDocuments()}. Potentially rewrites the query
* to be usable with {@code countDocuments()}.
*
* @return the query {@link Document} that can be used with {@code countDocuments()}.
*/
public Document toQueryDocument() {
if (!requiresRewrite(source)) {
return source;
}
Document target = new Document();
for (Map.Entry<String, Object> entry : source.entrySet()) {
if (entry.getValue() instanceof Document && requiresRewrite(entry.getValue())) {
Document theValue = (Document) entry.getValue();
target.putAll(createGeoWithin(entry.getKey(), theValue, source.get("$and")));
continue;
}
if (entry.getValue() instanceof Collection && requiresRewrite(entry.getValue())) {
Collection<?> source = (Collection<?>) entry.getValue();
target.put(entry.getKey(), rewriteCollection(source));
continue;
}
if ("$and".equals(entry.getKey()) && target.containsKey("$and")) {
// Expect $and to be processed with Document and createGeoWithin.
continue;
}
target.put(entry.getKey(), entry.getValue());
}
return target;
}
/**
* @param valueToInspect
* @return {@code true} if the enclosing element needs to be rewritten.
*/
private boolean requiresRewrite(Object valueToInspect) {
if (valueToInspect instanceof Document) {
return requiresRewrite((Document) valueToInspect);
}
if (valueToInspect instanceof Collection) {
return requiresRewrite((Collection<?>) valueToInspect);
}
return false;
}
private boolean requiresRewrite(Collection<?> collection) {
for (Object o : collection) {
if (o instanceof Document && requiresRewrite((Document) o)) {
return true;
}
}
return false;
}
private boolean requiresRewrite(Document document) {
if (containsNear(document)) {
return true;
}
for (Object entry : document.values()) {
if (requiresRewrite(entry)) {
return true;
}
}
return false;
}
private Collection<Object> rewriteCollection(Collection<?> source) {
Collection<Object> rewrittenCollection = new ArrayList<>(source.size());
for (Object item : source) {
if (item instanceof Document && requiresRewrite(item)) {
rewrittenCollection.add(CountQuery.of((Document) item).toQueryDocument());
} else {
rewrittenCollection.add(item);
}
}
return rewrittenCollection;
}
/**
* Rewrite the near query for field {@code key} to {@code $geoWithin}.
*
* @param key the queried field.
* @param source source {@link Document}.
* @param $and potentially existing {@code $and} condition.
* @return the rewritten query {@link Document}.
*/
@SuppressWarnings("unchecked")
private static Document createGeoWithin(String key, Document source, @Nullable Object $and) {
boolean spheric = source.containsKey("$nearSphere");
Object $near = spheric ? source.get("$nearSphere") : source.get("$near");
Number maxDistance = getMaxDistance(source, $near, spheric);
List<Object> $centerMax = Arrays.asList(toCenterCoordinates($near), maxDistance);
Document $geoWithinMax = new Document("$geoWithin",
new Document(spheric ? "$centerSphere" : "$center", $centerMax));
if (!containsNearWithMinDistance(source)) {
return new Document(key, $geoWithinMax);
}
Number minDistance = (Number) source.get("$minDistance");
List<Object> $centerMin = Arrays.asList(toCenterCoordinates($near), minDistance);
Document $geoWithinMin = new Document("$geoWithin",
new Document(spheric ? "$centerSphere" : "$center", $centerMin));
List<Document> criteria;
if ($and != null) {
if ($and instanceof Collection) {
Collection<Document> andElements = (Collection<Document>) $and;
criteria = new ArrayList<>(andElements.size() + 2);
criteria.addAll(andElements);
} else {
throw new IllegalArgumentException(
"Cannot rewrite query as it contains an '$and' element that is not a Collection: Offending element: "
+ $and);
}
} else {
criteria = new ArrayList<>(2);
}
criteria.add(new Document("$nor", Collections.singletonList(new Document(key, $geoWithinMin))));
criteria.add(new Document(key, $geoWithinMax));
return new Document("$and", criteria);
}
private static Number getMaxDistance(Document source, Object $near, boolean spheric) {
Number maxDistance = Double.MAX_VALUE;
if (source.containsKey("$maxDistance")) { // legacy coordinate pair
return (Number) source.get("$maxDistance");
}
if ($near instanceof Document nearDoc) {
if (nearDoc.containsKey("$maxDistance")) {
maxDistance = (Number) nearDoc.get("$maxDistance");
// geojson is in Meters but we need radians x/(6378.1*1000)
if (spheric && nearDoc.containsKey("$geometry")) {
maxDistance = MetricConversion.metersToRadians(maxDistance.doubleValue());
}
}
}
return maxDistance;
}
private static boolean containsNear(Document source) {
return source.containsKey("$near") || source.containsKey("$nearSphere");
}
private static boolean containsNearWithMinDistance(Document source) {
if (!containsNear(source)) {
return false;
}
return source.containsKey("$minDistance");
}
private static Object toCenterCoordinates(Object value) {
if (ObjectUtils.isArray(value)) {
return value;
}
if (value instanceof Point) {
return Arrays.asList(((Point) value).getX(), ((Point) value).getY());
}
if (value instanceof Document document) {
if (document.containsKey("x")) {
return Arrays.asList(document.get("x"), document.get("y"));
}
if (document.containsKey("$geometry")) {
Document geoJsonPoint = document.get("$geometry", Document.class);
return geoJsonPoint.get("coordinates");
}
}
return value;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,9 +15,15 @@
*/
package org.springframework.data.mongodb.core;
import org.bson.Document;
import java.util.function.Function;
import org.bson.Document;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import com.mongodb.ReadPreference;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
/**
* Simple callback interface to allow customization of a {@link FindIterable}.
@@ -25,12 +31,53 @@ import com.mongodb.client.FindIterable;
* @author Oliver Gierke
* @author Christoph Strobl
*/
interface CursorPreparer {
public interface CursorPreparer extends ReadPreferenceAware {
/**
* Default {@link CursorPreparer} just passing on the given {@link FindIterable}.
*
* @since 2.2
*/
CursorPreparer NO_OP_PREPARER = (iterable -> iterable);
/**
* Prepare the given cursor (apply limits, skips and so on). Returns the prepared cursor.
*
* @param cursor
* @param iterable must not be {@literal null}.
* @return never {@literal null}.
*/
FindIterable<Document> prepare(FindIterable<Document> cursor);
FindIterable<Document> prepare(FindIterable<Document> iterable);
/**
* Apply query specific settings to {@link MongoCollection} and initate a find operation returning a
* {@link FindIterable} via the given {@link Function find} function.
*
* @param collection must not be {@literal null}.
* @param find must not be {@literal null}.
* @return never {@literal null}.
* @throws IllegalArgumentException if one of the required arguments is {@literal null}.
* @since 2.2
*/
default FindIterable<Document> initiateFind(MongoCollection<Document> collection,
Function<MongoCollection<Document>, FindIterable<Document>> find) {
Assert.notNull(collection, "Collection must not be null");
Assert.notNull(find, "Find function must not be null");
if (hasReadPreference()) {
collection = collection.withReadPreference(getReadPreference());
}
return prepare(find.apply(collection));
}
/**
* @return the {@link ReadPreference} to apply or {@literal null} if none defined.
* @since 2.2
*/
@Override
@Nullable
default ReadPreference getReadPreference() {
return null;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2019 the original author or authors.
* Copyright 2010-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2019 the original author or authors.
* Copyright 2015-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,11 +24,13 @@ import java.util.stream.Collectors;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.mapping.callback.EntityCallbacks;
import org.springframework.data.mongodb.BulkOperationException;
import org.springframework.data.mongodb.core.convert.QueryMapper;
import org.springframework.data.mongodb.core.convert.UpdateMapper;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.event.AfterSaveCallback;
import org.springframework.data.mongodb.core.mapping.event.AfterSaveEvent;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertCallback;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
@@ -38,18 +40,19 @@ import org.springframework.data.mongodb.core.mapping.event.MongoMappingEvent;
import org.springframework.data.mongodb.core.query.Collation;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.data.mongodb.core.query.UpdateDefinition.ArrayFilter;
import org.springframework.data.util.Pair;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import com.mongodb.MongoBulkWriteException;
import com.mongodb.WriteConcern;
import com.mongodb.bulk.BulkWriteResult;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.*;
import lombok.NonNull;
import lombok.Value;
/**
* Default implementation for {@link BulkOperations}.
*
@@ -59,6 +62,9 @@ import lombok.Value;
* @author Mark Paluch
* @author Minsu Kim
* @author Jens Schauder
* @author Michail Nikolaev
* @author Roman Puchkovskiy
* @author Jacob Botuck
* @since 1.9
*/
class DefaultBulkOperations implements BulkOperations {
@@ -68,7 +74,6 @@ class DefaultBulkOperations implements BulkOperations {
private final BulkOperationContext bulkOperationContext;
private final List<SourceAwareWriteModelHolder> models = new ArrayList<>();
private PersistenceExceptionTranslator exceptionTranslator;
private @Nullable WriteConcern defaultWriteConcern;
private BulkWriteOptions bulkOptions;
@@ -85,26 +90,16 @@ class DefaultBulkOperations implements BulkOperations {
DefaultBulkOperations(MongoOperations mongoOperations, String collectionName,
BulkOperationContext bulkOperationContext) {
Assert.notNull(mongoOperations, "MongoOperations must not be null!");
Assert.hasText(collectionName, "CollectionName must not be null nor empty!");
Assert.notNull(bulkOperationContext, "BulkOperationContext must not be null!");
Assert.notNull(mongoOperations, "MongoOperations must not be null");
Assert.hasText(collectionName, "CollectionName must not be null nor empty");
Assert.notNull(bulkOperationContext, "BulkOperationContext must not be null");
this.mongoOperations = mongoOperations;
this.collectionName = collectionName;
this.bulkOperationContext = bulkOperationContext;
this.exceptionTranslator = new MongoExceptionTranslator();
this.bulkOptions = getBulkWriteOptions(bulkOperationContext.getBulkMode());
}
/**
* Configures the {@link PersistenceExceptionTranslator} to be used. Defaults to {@link MongoExceptionTranslator}.
*
* @param exceptionTranslator can be {@literal null}.
*/
public void setExceptionTranslator(@Nullable PersistenceExceptionTranslator exceptionTranslator) {
this.exceptionTranslator = exceptionTranslator == null ? new MongoExceptionTranslator() : exceptionTranslator;
}
/**
* Configures the default {@link WriteConcern} to be used. Defaults to {@literal null}.
*
@@ -114,14 +109,10 @@ class DefaultBulkOperations implements BulkOperations {
this.defaultWriteConcern = defaultWriteConcern;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.BulkOperations#insert(java.lang.Object)
*/
@Override
public BulkOperations insert(Object document) {
Assert.notNull(document, "Document must not be null!");
Assert.notNull(document, "Document must not be null");
maybeEmitEvent(new BeforeConvertEvent<>(document, collectionName));
Object source = maybeInvokeBeforeConvertCallback(document);
@@ -130,42 +121,30 @@ class DefaultBulkOperations implements BulkOperations {
return this;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.BulkOperations#insert(java.util.List)
*/
@Override
public BulkOperations insert(List<? extends Object> documents) {
Assert.notNull(documents, "Documents must not be null!");
Assert.notNull(documents, "Documents must not be null");
documents.forEach(this::insert);
return this;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.BulkOperations#updateOne(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.Update)
*/
@Override
@SuppressWarnings("unchecked")
public BulkOperations updateOne(Query query, Update update) {
Assert.notNull(query, "Query must not be null!");
Assert.notNull(update, "Update must not be null!");
Assert.notNull(query, "Query must not be null");
Assert.notNull(update, "Update must not be null");
return updateOne(Collections.singletonList(Pair.of(query, update)));
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.BulkOperations#updateOne(java.util.List)
*/
@Override
public BulkOperations updateOne(List<Pair<Query, Update>> updates) {
Assert.notNull(updates, "Updates must not be null!");
Assert.notNull(updates, "Updates must not be null");
for (Pair<Query, Update> update : updates) {
update(update.getFirst(), update.getSecond(), false, false);
@@ -174,28 +153,20 @@ class DefaultBulkOperations implements BulkOperations {
return this;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.BulkOperations#updateMulti(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.Update)
*/
@Override
@SuppressWarnings("unchecked")
public BulkOperations updateMulti(Query query, Update update) {
Assert.notNull(query, "Query must not be null!");
Assert.notNull(update, "Update must not be null!");
Assert.notNull(query, "Query must not be null");
Assert.notNull(update, "Update must not be null");
return updateMulti(Collections.singletonList(Pair.of(query, update)));
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.BulkOperations#updateMulti(java.util.List)
*/
@Override
public BulkOperations updateMulti(List<Pair<Query, Update>> updates) {
Assert.notNull(updates, "Updates must not be null!");
Assert.notNull(updates, "Updates must not be null");
for (Pair<Query, Update> update : updates) {
update(update.getFirst(), update.getSecond(), false, true);
@@ -204,19 +175,11 @@ class DefaultBulkOperations implements BulkOperations {
return this;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.BulkOperations#upsert(org.springframework.data.mongodb.core.query.Query, org.springframework.data.mongodb.core.query.Update)
*/
@Override
public BulkOperations upsert(Query query, Update update) {
return update(query, update, true, true);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.BulkOperations#upsert(java.util.List)
*/
@Override
public BulkOperations upsert(List<Pair<Query, Update>> updates) {
@@ -227,14 +190,10 @@ class DefaultBulkOperations implements BulkOperations {
return this;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.BulkOperations#remove(org.springframework.data.mongodb.core.query.Query)
*/
@Override
public BulkOperations remove(Query query) {
Assert.notNull(query, "Query must not be null!");
Assert.notNull(query, "Query must not be null");
DeleteOptions deleteOptions = new DeleteOptions();
query.getCollation().map(Collation::toMongoCollation).ifPresent(deleteOptions::collation);
@@ -244,14 +203,10 @@ class DefaultBulkOperations implements BulkOperations {
return this;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.BulkOperations#remove(java.util.List)
*/
@Override
public BulkOperations remove(List<Query> removes) {
Assert.notNull(removes, "Removals must not be null!");
Assert.notNull(removes, "Removals must not be null");
for (Query query : removes) {
remove(query);
@@ -260,16 +215,12 @@ class DefaultBulkOperations implements BulkOperations {
return this;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.BulkOperations#replaceOne(org.springframework.data.mongodb.core.query.Query, java.lang.Object, org.springframework.data.mongodb.core.FindAndReplaceOptions)
*/
@Override
public BulkOperations replaceOne(Query query, Object replacement, FindAndReplaceOptions options) {
Assert.notNull(query, "Query must not be null!");
Assert.notNull(replacement, "Replacement must not be null!");
Assert.notNull(options, "Options must not be null!");
Assert.notNull(query, "Query must not be null");
Assert.notNull(replacement, "Replacement must not be null");
Assert.notNull(options, "Options must not be null");
ReplaceOptions replaceOptions = new ReplaceOptions();
replaceOptions.upsert(options.isUpsert());
@@ -283,10 +234,6 @@ class DefaultBulkOperations implements BulkOperations {
return this;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.BulkOperations#executeBulk()
*/
@Override
public com.mongodb.bulk.BulkWriteResult execute() {
@@ -294,9 +241,10 @@ class DefaultBulkOperations implements BulkOperations {
com.mongodb.bulk.BulkWriteResult result = mongoOperations.execute(collectionName, this::bulkWriteTo);
Assert.state(result != null, "Result must not be null.");
Assert.state(result != null, "Result must not be null");
models.forEach(this::maybeEmitAfterSaveEvent);
models.forEach(this::maybeInvokeAfterSaveCallback);
return result;
} finally {
@@ -306,11 +254,30 @@ class DefaultBulkOperations implements BulkOperations {
private BulkWriteResult bulkWriteTo(MongoCollection<Document> collection) {
return collection.bulkWrite( //
models.stream() //
.map(this::extractAndMapWriteModel) //
.collect(Collectors.toList()), //
bulkOptions);
if (defaultWriteConcern != null) {
collection = collection.withWriteConcern(defaultWriteConcern);
}
try {
return collection.bulkWrite( //
models.stream() //
.map(this::extractAndMapWriteModel) //
.collect(Collectors.toList()), //
bulkOptions);
} catch (RuntimeException ex) {
if (ex instanceof MongoBulkWriteException) {
MongoBulkWriteException mongoBulkWriteException = (MongoBulkWriteException) ex;
if (mongoBulkWriteException.getWriteConcernError() != null) {
throw new DataIntegrityViolationException(ex.getMessage(), ex);
}
throw new BulkOperationException(ex.getMessage(), mongoBulkWriteException);
}
throw ex;
}
}
private WriteModel<Document> extractAndMapWriteModel(SourceAwareWriteModelHolder it) {
@@ -341,12 +308,10 @@ class DefaultBulkOperations implements BulkOperations {
*/
private BulkOperations update(Query query, Update update, boolean upsert, boolean multi) {
Assert.notNull(query, "Query must not be null!");
Assert.notNull(update, "Update must not be null!");
Assert.notNull(query, "Query must not be null");
Assert.notNull(update, "Update must not be null");
UpdateOptions options = new UpdateOptions();
options.upsert(upsert);
query.getCollation().map(Collation::toMongoCollation).ifPresent(options::collation);
UpdateOptions options = computeUpdateOptions(query, update, upsert);
if (multi) {
addModel(update, new UpdateManyModel<>(query.getQueryObject(), update.getUpdateObject(), options));
@@ -416,38 +381,52 @@ class DefaultBulkOperations implements BulkOperations {
models.add(new SourceAwareWriteModelHolder(source, model));
}
private void maybeEmitBeforeSaveEvent(SourceAwareWriteModelHolder it) {
private void maybeEmitBeforeSaveEvent(SourceAwareWriteModelHolder holder) {
if (it.getModel() instanceof InsertOneModel) {
if (holder.getModel() instanceof InsertOneModel) {
Document target = ((InsertOneModel<Document>) it.getModel()).getDocument();
maybeEmitEvent(new BeforeSaveEvent<>(it.getSource(), target, collectionName));
} else if (it.getModel() instanceof ReplaceOneModel) {
Document target = ((InsertOneModel<Document>) holder.getModel()).getDocument();
maybeEmitEvent(new BeforeSaveEvent<>(holder.getSource(), target, collectionName));
} else if (holder.getModel() instanceof ReplaceOneModel) {
Document target = ((ReplaceOneModel<Document>) it.getModel()).getReplacement();
maybeEmitEvent(new BeforeSaveEvent<>(it.getSource(), target, collectionName));
Document target = ((ReplaceOneModel<Document>) holder.getModel()).getReplacement();
maybeEmitEvent(new BeforeSaveEvent<>(holder.getSource(), target, collectionName));
}
}
private void maybeEmitAfterSaveEvent(SourceAwareWriteModelHolder it) {
private void maybeEmitAfterSaveEvent(SourceAwareWriteModelHolder holder) {
if (it.getModel() instanceof InsertOneModel) {
if (holder.getModel() instanceof InsertOneModel) {
Document target = ((InsertOneModel<Document>) it.getModel()).getDocument();
maybeEmitEvent(new AfterSaveEvent<>(it.getSource(), target, collectionName));
} else if (it.getModel() instanceof ReplaceOneModel) {
Document target = ((InsertOneModel<Document>) holder.getModel()).getDocument();
maybeEmitEvent(new AfterSaveEvent<>(holder.getSource(), target, collectionName));
} else if (holder.getModel() instanceof ReplaceOneModel) {
Document target = ((ReplaceOneModel<Document>) it.getModel()).getReplacement();
maybeEmitEvent(new AfterSaveEvent<>(it.getSource(), target, collectionName));
Document target = ((ReplaceOneModel<Document>) holder.getModel()).getReplacement();
maybeEmitEvent(new AfterSaveEvent<>(holder.getSource(), target, collectionName));
}
}
private void maybeInvokeAfterSaveCallback(SourceAwareWriteModelHolder holder) {
if (holder.getModel() instanceof InsertOneModel) {
Document target = ((InsertOneModel<Document>) holder.getModel()).getDocument();
maybeInvokeAfterSaveCallback(holder.getSource(), target);
} else if (holder.getModel() instanceof ReplaceOneModel) {
Document target = ((ReplaceOneModel<Document>) holder.getModel()).getReplacement();
maybeInvokeAfterSaveCallback(holder.getSource(), target);
}
}
private <E extends MongoMappingEvent<T>, T> E maybeEmitEvent(E event) {
if (null != bulkOperationContext.getEventPublisher()) {
bulkOperationContext.getEventPublisher().publishEvent(event);
if (bulkOperationContext.getEventPublisher() == null) {
return event;
}
bulkOperationContext.getEventPublisher().publishEvent(event);
return event;
}
@@ -470,6 +449,16 @@ class DefaultBulkOperations implements BulkOperations {
collectionName);
}
private Object maybeInvokeAfterSaveCallback(Object value, Document mappedDocument) {
if (bulkOperationContext.getEntityCallbacks() == null) {
return value;
}
return bulkOperationContext.getEntityCallbacks().callback(AfterSaveCallback.class, value, mappedDocument,
collectionName);
}
private static BulkWriteOptions getBulkWriteOptions(BulkMode bulkMode) {
BulkWriteOptions options = new BulkWriteOptions();
@@ -481,7 +470,30 @@ class DefaultBulkOperations implements BulkOperations {
return options.ordered(false);
}
throw new IllegalStateException("BulkMode was null!");
throw new IllegalStateException("BulkMode was null");
}
/**
* @param filterQuery The {@link Query} to read a potential {@link Collation} from. Must not be {@literal null}.
* @param update The {@link Update} to apply
* @param upsert flag to indicate if document should be upserted.
* @return new instance of {@link UpdateOptions}.
*/
private static UpdateOptions computeUpdateOptions(Query filterQuery, UpdateDefinition update, boolean upsert) {
UpdateOptions options = new UpdateOptions();
options.upsert(upsert);
if (update.hasArrayFilters()) {
List<Document> list = new ArrayList<>(update.getArrayFilters().size());
for (ArrayFilter arrayFilter : update.getArrayFilters()) {
list.add(arrayFilter.asDocument());
}
options.arrayFilters(list);
}
filterQuery.getCollation().map(Collation::toMongoCollation).ifPresent(options::collation);
return options;
}
/**
@@ -492,15 +504,93 @@ class DefaultBulkOperations implements BulkOperations {
* @author Christoph Strobl
* @since 2.0
*/
@Value
static class BulkOperationContext {
static final class BulkOperationContext {
@NonNull BulkMode bulkMode;
@NonNull Optional<? extends MongoPersistentEntity<?>> entity;
@NonNull QueryMapper queryMapper;
@NonNull UpdateMapper updateMapper;
ApplicationEventPublisher eventPublisher;
EntityCallbacks entityCallbacks;
private final BulkMode bulkMode;
private final Optional<? extends MongoPersistentEntity<?>> entity;
private final QueryMapper queryMapper;
private final UpdateMapper updateMapper;
private final ApplicationEventPublisher eventPublisher;
private final EntityCallbacks entityCallbacks;
BulkOperationContext(BulkOperations.BulkMode bulkMode, Optional<? extends MongoPersistentEntity<?>> entity,
QueryMapper queryMapper, UpdateMapper updateMapper, ApplicationEventPublisher eventPublisher,
EntityCallbacks entityCallbacks) {
this.bulkMode = bulkMode;
this.entity = entity;
this.queryMapper = queryMapper;
this.updateMapper = updateMapper;
this.eventPublisher = eventPublisher;
this.entityCallbacks = entityCallbacks;
}
public BulkMode getBulkMode() {
return this.bulkMode;
}
public Optional<? extends MongoPersistentEntity<?>> getEntity() {
return this.entity;
}
public QueryMapper getQueryMapper() {
return this.queryMapper;
}
public UpdateMapper getUpdateMapper() {
return this.updateMapper;
}
public ApplicationEventPublisher getEventPublisher() {
return this.eventPublisher;
}
public EntityCallbacks getEntityCallbacks() {
return this.entityCallbacks;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
BulkOperationContext that = (BulkOperationContext) o;
if (bulkMode != that.bulkMode)
return false;
if (!ObjectUtils.nullSafeEquals(this.entity, that.entity)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(this.queryMapper, that.queryMapper)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(this.updateMapper, that.updateMapper)) {
return false;
}
if (!ObjectUtils.nullSafeEquals(this.eventPublisher, that.eventPublisher)) {
return false;
}
return ObjectUtils.nullSafeEquals(this.entityCallbacks, that.entityCallbacks);
}
@Override
public int hashCode() {
int result = bulkMode != null ? bulkMode.hashCode() : 0;
result = 31 * result + ObjectUtils.nullSafeHashCode(entity);
result = 31 * result + ObjectUtils.nullSafeHashCode(queryMapper);
result = 31 * result + ObjectUtils.nullSafeHashCode(updateMapper);
result = 31 * result + ObjectUtils.nullSafeHashCode(eventPublisher);
result = 31 * result + ObjectUtils.nullSafeHashCode(entityCallbacks);
return result;
}
public String toString() {
return "DefaultBulkOperations.BulkOperationContext(bulkMode=" + this.getBulkMode() + ", entity="
+ this.getEntity() + ", queryMapper=" + this.getQueryMapper() + ", updateMapper=" + this.getUpdateMapper()
+ ", eventPublisher=" + this.getEventPublisher() + ", entityCallbacks=" + this.getEntityCallbacks() + ")";
}
}
/**
@@ -509,10 +599,50 @@ class DefaultBulkOperations implements BulkOperations {
* @since 2.2
* @author Christoph Strobl
*/
@Value
private static class SourceAwareWriteModelHolder {
private static final class SourceAwareWriteModelHolder {
Object source;
WriteModel<Document> model;
private final Object source;
private final WriteModel<Document> model;
SourceAwareWriteModelHolder(Object source, WriteModel<Document> model) {
this.source = source;
this.model = model;
}
public Object getSource() {
return this.source;
}
public WriteModel<Document> getModel() {
return this.model;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SourceAwareWriteModelHolder that = (SourceAwareWriteModelHolder) o;
if (!ObjectUtils.nullSafeEquals(this.source, that.source)) {
return false;
}
return ObjectUtils.nullSafeEquals(this.model, that.model);
}
@Override
public int hashCode() {
int result = ObjectUtils.nullSafeHashCode(model);
result = 31 * result + ObjectUtils.nullSafeHashCode(source);
return result;
}
public String toString() {
return "DefaultBulkOperations.SourceAwareWriteModelHolder(source=" + this.getSource() + ", model="
+ this.getModel() + ")";
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2011-2019 the original author or authors.
* Copyright 2011-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,7 +21,7 @@ import java.util.List;
import org.bson.Document;
import org.springframework.dao.DataAccessException;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.convert.QueryMapper;
import org.springframework.data.mongodb.core.index.IndexDefinition;
import org.springframework.data.mongodb.core.index.IndexInfo;
@@ -64,7 +64,7 @@ public class DefaultIndexOperations implements IndexOperations {
* {@link DefaultIndexOperations#DefaultIndexOperations(MongoOperations, String, Class)}.
*/
@Deprecated
public DefaultIndexOperations(MongoDbFactory mongoDbFactory, String collectionName, QueryMapper queryMapper) {
public DefaultIndexOperations(MongoDatabaseFactory mongoDbFactory, String collectionName, QueryMapper queryMapper) {
this(mongoDbFactory, collectionName, queryMapper, null);
}
@@ -80,12 +80,12 @@ public class DefaultIndexOperations implements IndexOperations {
* {@link DefaultIndexOperations#DefaultIndexOperations(MongoOperations, String, Class)}.
*/
@Deprecated
public DefaultIndexOperations(MongoDbFactory mongoDbFactory, String collectionName, QueryMapper queryMapper,
public DefaultIndexOperations(MongoDatabaseFactory mongoDbFactory, String collectionName, QueryMapper queryMapper,
@Nullable Class<?> type) {
Assert.notNull(mongoDbFactory, "MongoDbFactory must not be null!");
Assert.notNull(collectionName, "Collection name can not be null!");
Assert.notNull(queryMapper, "QueryMapper must not be null!");
Assert.notNull(mongoDbFactory, "MongoDbFactory must not be null");
Assert.notNull(collectionName, "Collection name can not be null");
Assert.notNull(queryMapper, "QueryMapper must not be null");
this.collectionName = collectionName;
this.mapper = queryMapper;
@@ -103,8 +103,8 @@ public class DefaultIndexOperations implements IndexOperations {
*/
public DefaultIndexOperations(MongoOperations mongoOperations, String collectionName, @Nullable Class<?> type) {
Assert.notNull(mongoOperations, "MongoOperations must not be null!");
Assert.hasText(collectionName, "Collection name must not be null or empty!");
Assert.notNull(mongoOperations, "MongoOperations must not be null");
Assert.hasText(collectionName, "Collection name must not be null or empty");
this.mongoOperations = mongoOperations;
this.mapper = new QueryMapper(mongoOperations.getConverter());
@@ -112,10 +112,6 @@ public class DefaultIndexOperations implements IndexOperations {
this.type = type;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.index.IndexOperations#ensureIndex(org.springframework.data.mongodb.core.index.IndexDefinition)
*/
public String ensureIndex(final IndexDefinition indexDefinition) {
return execute(collection -> {
@@ -127,7 +123,7 @@ public class DefaultIndexOperations implements IndexOperations {
indexOptions = addPartialFilterIfPresent(indexOptions, indexDefinition.getIndexOptions(), entity);
indexOptions = addDefaultCollationIfRequired(indexOptions, entity);
Document mappedKeys = mapper.getMappedObject(indexDefinition.getIndexKeys(), entity);
Document mappedKeys = mapper.getMappedSort(indexDefinition.getIndexKeys(), entity);
return collection.createIndex(mappedKeys, indexOptions);
});
}
@@ -150,10 +146,6 @@ public class DefaultIndexOperations implements IndexOperations {
return null;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.index.IndexOperations#dropIndex(java.lang.String)
*/
public void dropIndex(final String name) {
execute(collection -> {
@@ -163,18 +155,10 @@ public class DefaultIndexOperations implements IndexOperations {
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.index.IndexOperations#dropAllIndexes()
*/
public void dropAllIndexes() {
dropIndex("*");
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.index.IndexOperations#getIndexInfo()
*/
public List<IndexInfo> getIndexInfo() {
return execute(new CollectionCallback<List<IndexInfo>>() {
@@ -188,7 +172,8 @@ public class DefaultIndexOperations implements IndexOperations {
private List<IndexInfo> getIndexData(MongoCursor<Document> cursor) {
List<IndexInfo> indexInfoList = new ArrayList<>();
int available = cursor.available();
List<IndexInfo> indexInfoList = available > 0 ? new ArrayList<>(available) : new ArrayList<>();
while (cursor.hasNext()) {
@@ -205,7 +190,7 @@ public class DefaultIndexOperations implements IndexOperations {
@Nullable
public <T> T execute(CollectionCallback<T> callback) {
Assert.notNull(callback, "CollectionCallback must not be null!");
Assert.notNull(callback, "CollectionCallback must not be null");
if (type != null) {
return mongoOperations.execute(type, callback);
@@ -223,7 +208,7 @@ public class DefaultIndexOperations implements IndexOperations {
Assert.isInstanceOf(Document.class, sourceOptions.get(PARTIAL_FILTER_EXPRESSION_KEY));
return ops.partialFilterExpression(
mapper.getMappedObject((Document) sourceOptions.get(PARTIAL_FILTER_EXPRESSION_KEY), entity));
mapper.getMappedSort((Document) sourceOptions.get(PARTIAL_FILTER_EXPRESSION_KEY), entity));
}
private static IndexOptions addDefaultCollationIfRequired(IndexOptions ops, MongoPersistentEntity<?> entity) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016-2019 the original author or authors.
* Copyright 2016-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,13 +15,13 @@
*/
package org.springframework.data.mongodb.core;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.convert.QueryMapper;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.index.IndexOperationsProvider;
/**
* {@link IndexOperationsProvider} to obtain {@link IndexOperations} from a given {@link MongoDbFactory}.
* {@link IndexOperationsProvider} to obtain {@link IndexOperations} from a given {@link MongoDatabaseFactory}.
*
* @author Mark Paluch
* @author Christoph Strobl
@@ -29,25 +29,21 @@ import org.springframework.data.mongodb.core.index.IndexOperationsProvider;
*/
class DefaultIndexOperationsProvider implements IndexOperationsProvider {
private final MongoDbFactory mongoDbFactory;
private final MongoDatabaseFactory mongoDbFactory;
private final QueryMapper mapper;
/**
* @param mongoDbFactory must not be {@literal null}.
* @param mapper must not be {@literal null}.
*/
DefaultIndexOperationsProvider(MongoDbFactory mongoDbFactory, QueryMapper mapper) {
DefaultIndexOperationsProvider(MongoDatabaseFactory mongoDbFactory, QueryMapper mapper) {
this.mongoDbFactory = mongoDbFactory;
this.mapper = mapper;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.index.IndexOperationsProvider#reactiveIndexOps(java.lang.String)
*/
@Override
public IndexOperations indexOps(String collectionName) {
return new DefaultIndexOperations(mongoDbFactory, collectionName, mapper);
public IndexOperations indexOps(String collectionName, Class<?> type) {
return new DefaultIndexOperations(mongoDbFactory, collectionName, mapper, type);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016-2019 the original author or authors.
* Copyright 2016-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -76,9 +76,9 @@ public class DefaultReactiveIndexOperations implements ReactiveIndexOperations {
private DefaultReactiveIndexOperations(ReactiveMongoOperations mongoOperations, String collectionName,
QueryMapper queryMapper, Optional<Class<?>> type) {
Assert.notNull(mongoOperations, "ReactiveMongoOperations must not be null!");
Assert.notNull(collectionName, "Collection must not be null!");
Assert.notNull(queryMapper, "QueryMapper must not be null!");
Assert.notNull(mongoOperations, "ReactiveMongoOperations must not be null");
Assert.notNull(collectionName, "Collection must not be null");
Assert.notNull(queryMapper, "QueryMapper must not be null");
this.mongoOperations = mongoOperations;
this.collectionName = collectionName;
@@ -86,10 +86,6 @@ public class DefaultReactiveIndexOperations implements ReactiveIndexOperations {
this.type = type;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.index.ReactiveIndexOperations#ensureIndex(org.springframework.data.mongodb.core.index.IndexDefinition)
*/
public Mono<String> ensureIndex(final IndexDefinition indexDefinition) {
return mongoOperations.execute(collectionName, collection -> {
@@ -119,26 +115,14 @@ public class DefaultReactiveIndexOperations implements ReactiveIndexOperations {
.orElse(null);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.index.ReactiveIndexOperations#dropIndex(java.lang.String)
*/
public Mono<Void> dropIndex(final String name) {
return mongoOperations.execute(collectionName, collection -> collection.dropIndex(name)).then();
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.index.ReactiveIndexOperations#dropAllIndexes()
*/
public Mono<Void> dropAllIndexes() {
return dropIndex("*");
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.index.ReactiveIndexOperations#getIndexInfo()
*/
public Flux<IndexInfo> getIndexInfo() {
return mongoOperations.execute(collectionName, collection -> collection.listIndexes(Document.class)) //

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2019 the original author or authors.
* Copyright 2014-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,7 +31,6 @@ import org.bson.types.ObjectId;
import org.springframework.dao.DataAccessException;
import org.springframework.data.mongodb.core.script.ExecutableMongoScript;
import org.springframework.data.mongodb.core.script.NamedMongoScript;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
@@ -65,41 +64,29 @@ class DefaultScriptOperations implements ScriptOperations {
*/
public DefaultScriptOperations(MongoOperations mongoOperations) {
Assert.notNull(mongoOperations, "MongoOperations must not be null!");
Assert.notNull(mongoOperations, "MongoOperations must not be null");
this.mongoOperations = mongoOperations;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ScriptOperations#register(org.springframework.data.mongodb.core.script.ExecutableMongoScript)
*/
@Override
public NamedMongoScript register(ExecutableMongoScript script) {
return register(new NamedMongoScript(generateScriptName(), script));
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ScriptOperations#register(org.springframework.data.mongodb.core.script.NamedMongoScript)
*/
@Override
public NamedMongoScript register(NamedMongoScript script) {
Assert.notNull(script, "Script must not be null!");
Assert.notNull(script, "Script must not be null");
mongoOperations.save(script, SCRIPT_COLLECTION_NAME);
return script;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ScriptOperations#execute(org.springframework.data.mongodb.core.script.ExecutableMongoScript, java.lang.Object[])
*/
@Override
public Object execute(final ExecutableMongoScript script, final Object... args) {
Assert.notNull(script, "Script must not be null!");
Assert.notNull(script, "Script must not be null");
return mongoOperations.execute(new DbCallback<Object>() {
@@ -115,14 +102,10 @@ class DefaultScriptOperations implements ScriptOperations {
});
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ScriptOperations#call(java.lang.String, java.lang.Object[])
*/
@Override
public Object call(final String scriptName, final Object... args) {
Assert.hasText(scriptName, "ScriptName must not be null or empty!");
Assert.hasText(scriptName, "ScriptName must not be null or empty");
return mongoOperations.execute(new DbCallback<Object>() {
@@ -135,22 +118,14 @@ class DefaultScriptOperations implements ScriptOperations {
});
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ScriptOperations#exists(java.lang.String)
*/
@Override
public boolean exists(String scriptName) {
Assert.hasText(scriptName, "ScriptName must not be null or empty!");
Assert.hasText(scriptName, "ScriptName must not be null or empty");
return mongoOperations.exists(query(where("_id").is(scriptName)), NamedMongoScript.class, SCRIPT_COLLECTION_NAME);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ScriptOperations#getScriptNames()
*/
@Override
public Set<String> getScriptNames() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2019 the original author or authors.
* Copyright 2015-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2010-2019 the original author or authors.
* Copyright 2010-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,7 +23,7 @@ import com.mongodb.MongoException;
/**
* An interface used by {@link MongoTemplate} for processing documents returned from a MongoDB query on a per-document
* basis. Implementations of this interface perform the actual work of prcoessing each document but don't need to worry
* about exception handling. {@MongoException}s will be caught and translated by the calling MongoTemplate An
* about exception handling. {@link MongoException}s will be caught and translated by the calling MongoTemplate An
* DocumentCallbackHandler is typically stateful: It keeps the result state within the object, to be available later for
* later inspection.
*

Some files were not shown because too many files have changed in this diff Show More