Compare commits

..

126 Commits

Author SHA1 Message Date
Jens Schauder
6ce5a26dc6 Release version 3.1.12 (2020.0.12).
See #3734
2021-08-12 10:25:55 +02:00
Jens Schauder
2716d1d503 Prepare 3.1.12 (2020.0.12).
See #3734
2021-08-12 10:25:34 +02:00
Mark Paluch
32223fc00a 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:23:42 +02:00
Jens Schauder
1884b7a97a After release cleanups.
See #3681
2021-07-16 10:45:19 +02:00
Jens Schauder
1f670bb5ed Prepare next development iteration.
See #3681
2021-07-16 10:45:17 +02:00
Jens Schauder
3e97d47248 Release version 3.1.11 (2020.0.11).
See #3681
2021-07-16 10:19:52 +02:00
Jens Schauder
c02840ca30 Prepare 3.1.11 (2020.0.11).
See #3681
2021-07-16 10:18:57 +02:00
Jens Schauder
975768c0d6 Updated changelog.
See #3681
2021-07-16 10:18:49 +02:00
Christoph Strobl
323ec3f1d6 Polishing.
Simplify KeyMapper current property/index setup.

Original Pull Request: #3689
2021-07-06 12:32:08 +02:00
David Julia
e480ceb2b7 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 12:12:46 +02:00
Mark Paluch
9fedd8d8c3 Updated changelog.
See #3650
2021-06-22 16:07:27 +02:00
Mark Paluch
baddae25da After release cleanups.
See #3649
2021-06-22 15:28:51 +02:00
Mark Paluch
5064cf3e9a Prepare next development iteration.
See #3649
2021-06-22 15:28:47 +02:00
Mark Paluch
81271a4f2f Release version 3.1.10 (2020.0.10).
See #3649
2021-06-22 15:18:22 +02:00
Mark Paluch
c36f9988c7 Prepare 3.1.10 (2020.0.10).
See #3649
2021-06-22 15:17:54 +02:00
Mark Paluch
b49beb08b6 Updated changelog.
See #3649
2021-06-22 15:17:49 +02:00
Mark Paluch
18b0946879 Update reference docs to use correct MongoClient.
Closes #3666
2021-06-22 14:36:58 +02:00
larsw
cf3681f7c2 Add closing quote to GeoJson javadoc.
Closes #3677
2021-06-21 13:58:44 +02:00
Christoph Strobl
49ef3fbc74 Polishing.
Fix typo in class name and make sure MongoTestTemplate uses the configured simple types.

See: #3659
Original pull request: #3661.
2021-06-18 14:22:08 +02:00
Christoph Strobl
01141502a0 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:14:45 +02:00
Christoph Strobl
5d8f3d5c8b 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:55:46 +02:00
Mark Paluch
5cf801ff8e Polishing.
Add nullability annotation. Return early on null value conversion.

See #3633
Original pull request: #3643.
2021-06-09 14:20:46 +02:00
Christoph Strobl
2f3fb4aea9 Fix NPE in QueryMapper when trying to apply target type on null value.
Closes #3633
Original pull request: #3643.
2021-06-09 14:20:45 +02:00
Mark Paluch
82e05e7e8e Updated changelog.
See #3629
2021-05-14 12:36:39 +02:00
Mark Paluch
5be2e3eea2 After release cleanups.
See #3628
2021-05-14 12:05:20 +02:00
Mark Paluch
54f55e04de Prepare next development iteration.
See #3628
2021-05-14 12:05:16 +02:00
Mark Paluch
9ef1386784 Release version 3.1.9 (2020.0.9).
See #3628
2021-05-14 11:52:23 +02:00
Mark Paluch
696fd725c3 Prepare 3.1.9 (2020.0.9).
See #3628
2021-05-14 11:51:53 +02:00
Mark Paluch
e6fda2ccdd Updated changelog.
See #3628
2021-05-14 11:51:46 +02:00
Greg L. Turnquist
7a24bab9a2 Authenticate with artifactory.
See #3616.
2021-04-22 15:04:01 -05:00
Mark Paluch
38b7fb7105 Updated changelog.
See #3616
2021-04-14 14:40:02 +02:00
Mark Paluch
d42d06e058 After release cleanups.
See #3617
2021-04-14 11:42:08 +02:00
Mark Paluch
e2709abfe0 Prepare next development iteration.
See #3617
2021-04-14 11:42:04 +02:00
Mark Paluch
12b4aab834 Release version 3.1.8 (2020.0.8).
See #3617
2021-04-14 11:33:25 +02:00
Mark Paluch
db06756c8f Prepare 3.1.8 (2020.0.8).
See #3617
2021-04-14 11:32:47 +02:00
Mark Paluch
b319b8a589 Updated changelog.
See #3617
2021-04-14 11:32:42 +02:00
Mark Paluch
a516795759 Updated changelog.
See #3597
2021-04-14 11:17:41 +02:00
Mark Paluch
bab08502a5 Polishing.
Fix nullability annotations for isEqual(…) parameters. Fix generics. Reformat code.

Add tests.

See #3414
Original pull request: #3615.
2021-04-13 09:40:00 +02:00
Clement Petit
3e1f95bc94 Handle nested Pattern and Document in Criteria.equals(…).
Closes #3414
Original pull request: #3615.
2021-04-13 09:39:59 +02:00
Mark Paluch
5c153dc76e Polishing.
Use ObjectUtils for empty check.

See #3623
Original pull request: #3625.
2021-04-13 09:09:42 +02:00
Christoph Strobl
8f4e207d97 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:42 +02:00
Christoph Strobl
5000a40d72 Fix query mapping resolution of properties using underscore within field name.
Closes: #3601
Original pull request: #3607.
2021-04-09 12:27:08 +02:00
Mark Paluch
fb59f49dae After release cleanups.
See #3598
2021-03-31 18:29:41 +02:00
Mark Paluch
f3c1e014e9 Prepare next development iteration.
See #3598
2021-03-31 18:29:38 +02:00
Mark Paluch
f52cc3be1f Release version 3.1.7 (2020.0.7).
See #3598
2021-03-31 18:19:52 +02:00
Mark Paluch
1bda93858c Prepare 3.1.7 (2020.0.7).
See #3598
2021-03-31 18:19:19 +02:00
Mark Paluch
1808970daf Updated changelog.
See #3598
2021-03-31 18:19:13 +02:00
Mark Paluch
558fc28cce Updated changelog.
See #3595
2021-03-31 17:26:09 +02:00
Mark Paluch
16bef54f11 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:50 +02:00
Mark Paluch
d68a812e1b 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 11:02:34 +02:00
Clément Petit
ccb9f111d9 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:36 +02:00
Mark Paluch
f64b177c8f Updated changelog.
See #3558
2021-03-17 11:31:32 +01:00
Mark Paluch
c0c7ba767f After release cleanups.
See #3561
2021-03-17 11:02:15 +01:00
Mark Paluch
7639701f3f Prepare next development iteration.
See #3561
2021-03-17 11:02:13 +01:00
Mark Paluch
b39b2591b6 Release version 3.1.6 (2020.0.6).
See #3561
2021-03-17 10:54:12 +01:00
Mark Paluch
65c8317e38 Prepare 3.1.6 (2020.0.6).
See #3561
2021-03-17 10:53:43 +01:00
Mark Paluch
9d0f7bac6a Updated changelog.
See #3561
2021-03-17 10:53:41 +01:00
Mark Paluch
6f50747d21 Updated changelog.
See #3556
2021-03-17 10:35:15 +01:00
Mark Paluch
5cf1578ad3 Polishing.
Move hasValue(…) from DocumentAccessor to BsonUtils. Fix typo in tests.

See: #3590
Original pull request: #3591.
2021-03-15 14:03:33 +01:00
Christoph Strobl
78a59c45ca 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:02:49 +01:00
Christoph Strobl
dccdfc8b4d Upgrade MongoDB drivers to 4.1.2
Closes #3589
2021-03-15 09:17:52 +01:00
Mark Paluch
e48239eb8f 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:08:05 +01:00
Christoph Strobl
c3b4f61d29 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:20 +01:00
Mark Paluch
22ed860b4a 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:26 +01:00
Brice Vandeputte
bf642ad3f7 Translate MongoSocketException subclasses to DataAccessResourceFailureException.
Closes #3568
Original pull request: #3569.
2021-03-02 11:30:26 +01:00
Christoph Strobl
fcd48539ea Remove duplicate JSON Schema section from reference documentation.
Closes: #3573
Original pull request: #3574.
2021-03-01 14:42:33 +01:00
Mark Paluch
bf10f72a57 Polishing.
Simplify assertions.

See #3552.
Original pull request: #3565.
2021-02-22 09:57:03 +01:00
Christoph Strobl
1c652cce1c 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:57:02 +01:00
Mark Paluch
dc2de878bc Polishing.
Reformat code. Add since tags.

See #3395
Original pull request: #3554.
2021-02-18 15:08:49 +01:00
Christoph Strobl
00cacc02ac 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:49 +01:00
Christoph Strobl
811c2e5d7b Updated changelog.
See #3560
2021-02-18 11:37:47 +01:00
Christoph Strobl
200f3006bd After release cleanups.
See #3557
2021-02-18 11:12:46 +01:00
Christoph Strobl
1d6bea51ec Prepare next development iteration.
See #3557
2021-02-18 11:12:44 +01:00
Christoph Strobl
7779ded45c Release version 3.1.5 (2020.0.5).
See #3557
2021-02-18 10:59:16 +01:00
Christoph Strobl
918bf7c138 Prepare 3.1.5 (2020.0.5).
See #3557
2021-02-18 10:58:49 +01:00
Christoph Strobl
abe3b9f6d7 Updated changelog.
See #3557
2021-02-18 10:58:42 +01:00
Christoph Strobl
41c453cc83 Updated changelog.
See #3537
2021-02-17 14:20:39 +01:00
Christoph Strobl
77784d88c7 After release cleanups.
See #3536
2021-02-17 13:41:54 +01:00
Christoph Strobl
263c62c880 Prepare next development iteration.
See #3536
2021-02-17 13:41:53 +01:00
Christoph Strobl
24ab8f67bb Release version 3.1.4 (2020.0.4).
See #3536
2021-02-17 12:00:24 +01:00
Christoph Strobl
572ceb867e Prepare 3.1.4 (2020.0.4).
See #3536
2021-02-17 11:59:37 +01:00
Christoph Strobl
b7caea8602 Updated changelog.
See #3536
2021-02-17 11:59:32 +01:00
Christoph Strobl
3696f2144f Updated changelog.
See #3520
2021-02-17 11:34:25 +01:00
Christoph Strobl
b25c8acca6 Updated changelog.
See #3519
2021-02-17 10:58:24 +01:00
Christoph Strobl
00d6271468 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:47:49 +01:00
Christoph Strobl
bb603ba7b9 Updated reference documentation regarding GeoJsonModule.
Original pull request: #3539.
Closes #3517
2021-02-02 14:50:54 +01:00
Christoph Strobl
02eaa4cbd2 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:22:15 +01:00
Christoph Strobl
7429503c63 Update count vs. estimatedCount documentation.
Closes #3055
Original pull request: #3541.
2021-02-02 14:22:15 +01:00
Christoph Strobl
82f4e2276b 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:14:52 +01:00
Mark Paluch
e1bce7d942 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:39 +01:00
wonwoo
8bf3d395be Add missing ReactiveMongoOperations.aggregate Kotlin extension.
See #3508.
Original pull request: #893.
2021-01-27 09:57:39 +01:00
Christoph Strobl
d3c00a93c0 Update QBE Documentation section.
This commit adds a note explaining scenarios suitable for an UntypedExampleMatcher.

Closes: #3474
Original pull request: #3538.
2021-01-26 15:04:10 +01:00
Christoph Strobl
0aa805e1a2 Fix method names in full text query documentation.
Closes #3525
2021-01-20 08:29:52 +01:00
Christoph Strobl
9dc1df3deb Updated changelog.
See #3521
2021-01-13 15:49:50 +01:00
Christoph Strobl
92a73a5cc0 After release cleanups.
See #3477
2021-01-13 15:01:50 +01:00
Christoph Strobl
910d66afb0 Prepare next development iteration.
See #3477
2021-01-13 15:01:46 +01:00
Christoph Strobl
1b60eae771 Release version 3.1.3 (2020.0.3).
See #3477
2021-01-13 14:18:34 +01:00
Christoph Strobl
60dfdd7de6 Prepare 3.1.3 (2020.0.3).
See #3477
2021-01-13 14:17:43 +01:00
Christoph Strobl
4ec48c376d Updated changelog.
See #3477
2021-01-13 14:17:35 +01:00
Christoph Strobl
dee2ba15a4 Update issue tracker references after GitHub issues migration.
See: #3529
2021-01-12 13:57:14 +01:00
Mark Paluch
c3596a503c Update copyright year to 2021.
Closes #3534
2021-01-12 11:50:08 +01:00
Mark Paluch
7dca5a2218 DATAMONGO-2671 - Polishing.
Fix copyright header.

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

Original pull request: #897.
2021-01-11 12:15:15 +01:00
Christoph Strobl
a0d5c2bded 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:37 +01:00
Greg L. Turnquist
c697fe57c9 DATAMONGO-2665 - Use Docker hub credentials for all CI jobs, 2020-12-15 15:22:42 -06:00
Mark Paluch
8a23452fdc DATAMONGO-2653 - After release cleanups. 2020-12-09 16:46:53 +01:00
Mark Paluch
bec7023a43 DATAMONGO-2653 - Prepare next development iteration. 2020-12-09 16:46:46 +01:00
Mark Paluch
89a7309707 DATAMONGO-2653 - Release version 3.1.2 (2020.0.2). 2020-12-09 16:01:24 +01:00
Mark Paluch
55ec9c5e5b DATAMONGO-2653 - Prepare 3.1.2 (2020.0.2). 2020-12-09 16:00:53 +01:00
Mark Paluch
cbb4dcb025 DATAMONGO-2653 - Updated changelog. 2020-12-09 16:00:49 +01:00
Mark Paluch
a0bad13505 DATAMONGO-2649 - Updated changelog. 2020-12-09 15:33:27 +01:00
Mark Paluch
d13521ae5d DATAMONGO-2647 - Updated changelog. 2020-12-09 12:42:29 +01:00
Mark Paluch
51f1526214 DATAMONGO-2646 - Updated changelog. 2020-12-09 09:59:14 +01:00
Mark Paluch
d049d96952 DATAMONGO-2663 - Document Spring Data to MongoDB compatibility.
Original Pull Request: #895
2020-12-07 14:39:32 +01:00
Mark Paluch
885bf0eae9 DATAMONGO-2661 - Polishing.
Add ticket reference.

Original pull request: #894.
2020-11-26 11:46:31 +01:00
Yoann de Martino
2a8ffd53d8 DATAMONGO-2661 - Handle nullable types for KPropertyPath.
Original pull request: #894.
2020-11-26 11:46:24 +01:00
Mark Paluch
d54ed61581 DATAMONGO-2648 - After release cleanups. 2020-11-11 12:14:53 +01:00
Mark Paluch
9e76da91a9 DATAMONGO-2648 - Prepare next development iteration. 2020-11-11 12:14:50 +01:00
Mark Paluch
595fde7b04 DATAMONGO-2648 - Release version 3.1.1 (2020.0.1). 2020-11-11 11:58:58 +01:00
Mark Paluch
01f4e73b48 DATAMONGO-2648 - Prepare 3.1.1 (2020.0.1). 2020-11-11 11:58:35 +01:00
Mark Paluch
2934c4886b DATAMONGO-2648 - Updated changelog. 2020-11-11 11:58:18 +01:00
Christoph Strobl
080c798721 DATAMONGO-2644 - ProjectOperation no longer errors on inclusion of default _id field.
Original pull request: #890.
2020-11-10 09:40:49 +01:00
Christoph Strobl
7cfb68e6be 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:40:49 +01:00
Mark Paluch
1e24abe8e5 DATAMONGO-2639 - Enable maintenance branch build. 2020-10-29 09:43:58 +01:00
Mark Paluch
a316d156dc DATAMONGO-2639 - After release cleanups. 2020-10-28 16:10:54 +01:00
Mark Paluch
6563b125eb DATAMONGO-2639 - Prepare next development iteration. 2020-10-28 16:10:50 +01:00
170 changed files with 3072 additions and 12980 deletions

View File

@@ -6,6 +6,7 @@ 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).

View File

@@ -1,47 +0,0 @@
# 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,6 +1,6 @@
= 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%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/]

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/main/CONTRIBUTING.adoc[here].
You find the contribution guidelines for Spring Data projects https://github.com/spring-projects/spring-data-build/blob/master/CONTRIBUTING.adoc[here].

36
Jenkinsfile vendored
View File

@@ -3,7 +3,7 @@ pipeline {
triggers {
pollSCM 'H/10 * * * *'
upstream(upstreamProjects: "spring-data-commons/main", threshold: hudson.model.Result.SUCCESS)
upstream(upstreamProjects: "spring-data-commons/2.4.x", threshold: hudson.model.Result.SUCCESS)
}
options {
@@ -23,39 +23,39 @@ pipeline {
steps {
script {
def image = docker.build("springci/spring-data-openjdk8-with-mongodb-4.0.23", "ci/openjdk8-mongodb-4.0/")
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.4') {
stage('Publish JDK 8 + MongoDB 4.2') {
when {
changeset "ci/openjdk8-mongodb-4.4/**"
changeset "ci/openjdk8-mongodb-4.2/**"
}
agent { label 'data' }
options { timeout(time: 30, unit: 'MINUTES') }
steps {
script {
def image = docker.build("springci/spring-data-openjdk8-with-mongodb-4.4.4", "ci/openjdk8-mongodb-4.4/")
def image = docker.build("springci/spring-data-openjdk8-with-mongodb-4.2.0", "ci/openjdk8-mongodb-4.2/")
docker.withRegistry('', 'hub.docker.com-springbuildmaster') {
image.push()
}
}
}
}
stage('Publish JDK 16 + MongoDB 4.4') {
stage('Publish JDK 15 + MongoDB 4.2') {
when {
changeset "ci/openjdk16-mongodb-4.4/**"
changeset "ci/openjdk15-mongodb-4.2/**"
}
agent { label 'data' }
options { timeout(time: 30, unit: 'MINUTES') }
steps {
script {
def image = docker.build("springci/spring-data-openjdk16-with-mongodb-4.4.4", "ci/openjdk16-mongodb-4.4/")
def image = docker.build("springci/spring-data-openjdk15-with-mongodb-4.2.0", "ci/openjdk15-mongodb-4.2/")
docker.withRegistry('', 'hub.docker.com-springbuildmaster') {
image.push()
}
@@ -68,7 +68,7 @@ pipeline {
stage("test: baseline (jdk8)") {
when {
anyOf {
branch 'main'
branch '3.1.x'
not { triggeredBy 'UpstreamCause' }
}
}
@@ -82,7 +82,7 @@ pipeline {
steps {
script {
docker.withRegistry('', 'hub.docker.com-springbuildmaster') {
docker.image('springci/spring-data-openjdk8-with-mongodb-4.0.23:latest').inside('-v $HOME:/tmp/jenkins-home') {
docker.image('springci/spring-data-openjdk8-with-mongodb-4.2.0:latest').inside('-v $HOME:/tmp/jenkins-home') {
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'
@@ -98,7 +98,7 @@ pipeline {
stage("Test other configurations") {
when {
allOf {
branch 'main'
branch '3.1.x'
not { triggeredBy 'UpstreamCause' }
}
}
@@ -114,7 +114,7 @@ pipeline {
steps {
script {
docker.withRegistry('', 'hub.docker.com-springbuildmaster') {
docker.image('springci/spring-data-openjdk8-with-mongodb-4.0.23:latest').inside('-v $HOME:/tmp/jenkins-home') {
docker.image('springci/spring-data-openjdk8-with-mongodb-4.0:latest').inside('-v $HOME:/tmp/jenkins-home') {
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'
@@ -127,7 +127,7 @@ pipeline {
}
}
stage("test: mongodb 4.4 (jdk8)") {
stage("test: mongodb 4.2 (jdk8)") {
agent {
label 'data'
}
@@ -138,7 +138,7 @@ pipeline {
steps {
script {
docker.withRegistry('', 'hub.docker.com-springbuildmaster') {
docker.image('springci/spring-data-openjdk8-with-mongodb-4.4.4:latest').inside('-v $HOME:/tmp/jenkins-home') {
docker.image('springci/spring-data-openjdk8-with-mongodb-4.2.0:latest').inside('-v $HOME:/tmp/jenkins-home') {
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'
@@ -151,7 +151,7 @@ pipeline {
}
}
stage("test: baseline (jdk16)") {
stage("test: baseline (jdk15)") {
agent {
label 'data'
}
@@ -162,7 +162,7 @@ pipeline {
steps {
script {
docker.withRegistry('', 'hub.docker.com-springbuildmaster') {
docker.image('springci/spring-data-openjdk16-with-mongodb-4.4.4:latest').inside('-v $HOME:/tmp/jenkins-home') {
docker.image('springci/spring-data-openjdk15-with-mongodb-4.2.0:latest').inside('-v $HOME:/tmp/jenkins-home') {
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'
@@ -180,7 +180,7 @@ pipeline {
stage('Release to artifactory') {
when {
anyOf {
branch 'main'
branch '3.1.x'
not { triggeredBy 'UpstreamCause' }
}
}
@@ -213,7 +213,7 @@ pipeline {
stage('Publish documentation') {
when {
branch 'main'
branch '3.1.x'
}
agent {
label 'data'

View File

@@ -1,6 +1,6 @@
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]
= 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 image:https://jenkins.spring.io/buildStatus/icon?job=spring-data-mongodb%2Fmaster&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]]
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.

View File

@@ -5,11 +5,11 @@ ENV DEBIAN_FRONTEND=noninteractive
RUN set -eux; \
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 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-4.4.list; \
apt-key adv --keyserver hkps://keyserver.ubuntu.com:443 --recv e162f504a20cdf15827f718d4b7c549a058f8b6b ; \
echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-4.2.list; \
echo ${TZ} > /etc/timezone;
RUN apt-get update ; \
apt-get install -y mongodb-org=4.4.4 mongodb-org-server=4.4.4 mongodb-org-shell=4.4.4 mongodb-org-mongos=4.4.4 mongodb-org-tools=4.4.4 ; \
apt-get install -y mongodb-org=4.2.0 mongodb-org-server=4.2.0 mongodb-org-shell=4.2.0 mongodb-org-mongos=4.2.0 mongodb-org-tools=4.2.0 ; \
apt-get clean; \
rm -rf /var/lib/apt/lists/*;

View File

@@ -1,15 +1,15 @@
FROM adoptopenjdk/openjdk16:latest
FROM adoptopenjdk/openjdk15:latest
ENV TZ=Etc/UTC
ENV DEBIAN_FRONTEND=noninteractive
RUN set -eux; \
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 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-4.4.list; \
apt-key adv --keyserver hkps://keyserver.ubuntu.com:443 --recv e162f504a20cdf15827f718d4b7c549a058f8b6b ; \
echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-4.2.list; \
echo ${TZ} > /etc/timezone;
RUN apt-get update ; \
apt-get install -y mongodb-org=4.4.4 mongodb-org-server=4.4.4 mongodb-org-shell=4.4.4 mongodb-org-mongos=4.4.4 mongodb-org-tools=4.4.4 ; \
apt-get install -y mongodb-org=4.2.0 mongodb-org-server=4.2.0 mongodb-org-shell=4.2.0 mongodb-org-mongos=4.2.0 mongodb-org-tools=4.2.0 ; \
apt-get clean; \
rm -rf /var/lib/apt/lists/*;

View File

@@ -10,6 +10,6 @@ RUN RUN set -eux; \
echo ${TZ} > /etc/timezone;
RUN apt-get update ; \
apt-get install -y mongodb-org=4.0.23 mongodb-org-server=4.0.23 mongodb-org-shell=4.0.23 mongodb-org-mongos=4.0.23 mongodb-org-tools=4.0.23 ; \
apt-get install -y mongodb-org=4.0.14 mongodb-org-server=4.0.14 mongodb-org-shell=4.0.14 mongodb-org-mongos=4.0.14 mongodb-org-tools=4.0.14 ; \
apt-get clean; \
rm -rf /var/lib/apt/lists/*;

View File

@@ -5,13 +5,11 @@ ENV DEBIAN_FRONTEND=noninteractive
RUN set -eux; \
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 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-4.4.list; \
apt-key adv --keyserver hkps://keyserver.ubuntu.com:443 --recv e162f504a20cdf15827f718d4b7c549a058f8b6b ; \
echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-4.2.list; \
echo ${TZ} > /etc/timezone;
RUN apt-get update ; \
ln -T /bin/true /usr/bin/systemctl ; \
apt-get install -y mongodb-org=4.4.4 mongodb-org-server=4.4.4 mongodb-org-shell=4.4.4 mongodb-org-mongos=4.4.4 mongodb-org-tools=4.4.4 ; \
rm /usr/bin/systemctl ; \
apt-get install -y mongodb-org=4.2.0 mongodb-org-server=4.2.0 mongodb-org-shell=4.2.0 mongodb-org-mongos=4.2.0 mongodb-org-tools=4.2.0 ; \
apt-get clean; \
rm -rf /var/lib/apt/lists/*;

12
pom.xml
View File

@@ -5,7 +5,7 @@
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>3.3.0-M2</version>
<version>3.1.12</version>
<packaging>pom</packaging>
<name>Spring Data MongoDB</name>
@@ -15,7 +15,7 @@
<parent>
<groupId>org.springframework.data.build</groupId>
<artifactId>spring-data-parent</artifactId>
<version>2.6.0-M2</version>
<version>2.4.12</version>
</parent>
<modules>
@@ -26,8 +26,8 @@
<properties>
<project.type>multi</project.type>
<dist.id>spring-data-mongodb</dist.id>
<springdata.commons>2.6.0-M2</springdata.commons>
<mongo>4.3.0</mongo>
<springdata.commons>2.4.12</springdata.commons>
<mongo>4.1.2</mongo>
<mongo.reactivestreams>${mongo}</mongo.reactivestreams>
<jmh.version>1.19</jmh.version>
</properties>
@@ -134,8 +134,8 @@
<repositories>
<repository>
<id>spring-libs-milestone</id>
<url>https://repo.spring.io/libs-milestone</url>
<id>spring-libs-release</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>sonatype-libs-snapshot</id>

View File

@@ -7,7 +7,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>3.3.0-M2</version>
<version>3.1.12</version>
<relativePath>../pom.xml</relativePath>
</parent>

View File

@@ -14,7 +14,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>3.3.0-M2</version>
<version>3.1.12</version>
<relativePath>../pom.xml</relativePath>
</parent>

View File

@@ -11,7 +11,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>3.3.0-M2</version>
<version>3.1.12</version>
<relativePath>../pom.xml</relativePath>
</parent>
@@ -87,13 +87,6 @@
<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>

View File

@@ -1,152 +0,0 @@
/*
* Copyright 2021 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()}.
* <p />
*
* <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);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.MongoExpression#toDocument()
*/
@Override
public Document toDocument() {
return target.get();
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@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,73 +0,0 @@
/*
* Copyright 2021 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.
* <p />
* 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

@@ -27,7 +27,6 @@ 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.AggregationOptions.DomainTypeMapping;
import org.springframework.data.mongodb.core.aggregation.CountOperation;
import org.springframework.data.mongodb.core.aggregation.RelaxedTypeBasedAggregationOperationContext;
import org.springframework.data.mongodb.core.aggregation.TypeBasedAggregationOperationContext;
@@ -37,7 +36,6 @@ 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;
@@ -54,46 +52,41 @@ class AggregationUtil {
QueryMapper queryMapper;
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext;
Lazy<AggregationOperationContext> untypedMappingContext;
AggregationUtil(QueryMapper queryMapper,
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext) {
this.queryMapper = queryMapper;
this.mappingContext = mappingContext;
this.untypedMappingContext = Lazy
.of(() -> new RelaxedTypeBasedAggregationOperationContext(Object.class, mappingContext, queryMapper));
}
AggregationOperationContext createAggregationContext(Aggregation aggregation, @Nullable Class<?> inputType) {
/**
* 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) {
DomainTypeMapping domainTypeMapping = aggregation.getOptions().getDomainTypeMapping();
if (domainTypeMapping == DomainTypeMapping.NONE) {
return Aggregation.DEFAULT_CONTEXT;
if (context != null) {
return context;
}
if (!(aggregation instanceof TypedAggregation)) {
return new RelaxedTypeBasedAggregationOperationContext(Object.class, mappingContext, queryMapper);
}
if(inputType == null) {
return untypedMappingContext.get();
}
if (domainTypeMapping == DomainTypeMapping.STRICT
&& !aggregation.getPipeline().containsUnionWith()) {
return new TypeBasedAggregationOperationContext(inputType, mappingContext, queryMapper);
}
Class<?> inputType = ((TypedAggregation) aggregation).getInputType();
if (aggregation.getPipeline().containsUnionWith()) {
return new RelaxedTypeBasedAggregationOperationContext(inputType, mappingContext, queryMapper);
}
inputType = ((TypedAggregation<?>) aggregation).getInputType();
if (domainTypeMapping == DomainTypeMapping.STRICT
&& !aggregation.getPipeline().containsUnionWith()) {
return new TypeBasedAggregationOperationContext(inputType, mappingContext, queryMapper);
}
return new RelaxedTypeBasedAggregationOperationContext(inputType, mappingContext, queryMapper);
return new TypeBasedAggregationOperationContext(inputType, mappingContext, queryMapper);
}
/**
@@ -132,6 +125,53 @@ class AggregationUtil {
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);
}
private List<Document> mapAggregationPipeline(List<Document> pipeline) {
return pipeline.stream().map(val -> queryMapper.getMappedObject(val, Optional.empty()))

View File

@@ -17,11 +17,8 @@ package org.springframework.data.mongodb.core;
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;
@@ -45,7 +42,6 @@ public class CollectionOptions {
private @Nullable Boolean capped;
private @Nullable Collation collation;
private ValidationOptions validationOptions;
private @Nullable TimeSeriesOptions timeSeriesOptions;
/**
* Constructs a new <code>CollectionOptions</code> instance.
@@ -58,19 +54,17 @@ public class CollectionOptions {
*/
@Deprecated
public CollectionOptions(@Nullable Long size, @Nullable Long maxDocuments, @Nullable Boolean capped) {
this(size, maxDocuments, capped, null, ValidationOptions.none(), null);
this(size, maxDocuments, capped, null, ValidationOptions.none());
}
private CollectionOptions(@Nullable Long size, @Nullable Long maxDocuments, @Nullable Boolean capped,
@Nullable Collation collation, ValidationOptions validationOptions,
@Nullable TimeSeriesOptions timeSeriesOptions) {
@Nullable Collation collation, ValidationOptions validationOptions) {
this.maxDocuments = maxDocuments;
this.size = size;
this.capped = capped;
this.collation = collation;
this.validationOptions = validationOptions;
this.timeSeriesOptions = timeSeriesOptions;
}
/**
@@ -84,7 +78,7 @@ public class CollectionOptions {
Assert.notNull(collation, "Collation must not be null!");
return new CollectionOptions(null, null, null, collation, ValidationOptions.none(), null);
return new CollectionOptions(null, null, null, collation, ValidationOptions.none());
}
/**
@@ -94,21 +88,7 @@ public class CollectionOptions {
* @since 2.0
*/
public static CollectionOptions empty() {
return new CollectionOptions(null, null, null, null, ValidationOptions.none(), 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));
return new CollectionOptions(null, null, null, null, ValidationOptions.none());
}
/**
@@ -119,7 +99,7 @@ public class CollectionOptions {
* @since 2.0
*/
public CollectionOptions capped() {
return new CollectionOptions(size, maxDocuments, true, collation, validationOptions, null);
return new CollectionOptions(size, maxDocuments, true, collation, validationOptions);
}
/**
@@ -130,7 +110,7 @@ public class CollectionOptions {
* @since 2.0
*/
public CollectionOptions maxDocuments(long maxDocuments) {
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions, timeSeriesOptions);
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions);
}
/**
@@ -141,7 +121,7 @@ public class CollectionOptions {
* @since 2.0
*/
public CollectionOptions size(long size) {
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions, timeSeriesOptions);
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions);
}
/**
@@ -152,7 +132,7 @@ public class CollectionOptions {
* @since 2.0
*/
public CollectionOptions collation(@Nullable Collation collation) {
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions, timeSeriesOptions);
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions);
}
/**
@@ -272,20 +252,7 @@ public class CollectionOptions {
public CollectionOptions validation(ValidationOptions validationOptions) {
Assert.notNull(validationOptions, "ValidationOptions must not be null!");
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions, timeSeriesOptions);
}
/**
* 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);
return new CollectionOptions(size, maxDocuments, capped, collation, validationOptions);
}
/**
@@ -336,16 +303,6 @@ 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);
}
/**
* Encapsulation of ValidationOptions options.
*
@@ -441,89 +398,4 @@ public class CollectionOptions {
return !Optionals.isAnyPresent(getValidator(), getValidationAction(), getValidationLevel());
}
}
/**
* 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;
}
}
}

View File

@@ -47,7 +47,7 @@ class DefaultIndexOperationsProvider implements IndexOperationsProvider {
* @see org.springframework.data.mongodb.core.index.IndexOperationsProvider#reactiveIndexOps(java.lang.String)
*/
@Override
public IndexOperations indexOps(String collectionName, Class<?> type) {
return new DefaultIndexOperations(mongoDbFactory, collectionName, mapper, type);
public IndexOperations indexOps(String collectionName) {
return new DefaultIndexOperations(mongoDbFactory, collectionName, mapper);
}
}

View File

@@ -16,7 +16,6 @@
package org.springframework.data.mongodb.core;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
@@ -29,23 +28,18 @@ import org.springframework.data.mapping.PersistentEntity;
import org.springframework.data.mapping.PersistentPropertyAccessor;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mapping.model.ConvertingPropertyAccessor;
import org.springframework.data.mongodb.core.CollectionOptions.TimeSeriesOptions;
import org.springframework.data.mongodb.core.convert.MongoWriter;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.core.mapping.MongoSimpleTypes;
import org.springframework.data.mongodb.core.mapping.TimeSeries;
import org.springframework.data.mongodb.core.query.Collation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.timeseries.Granularity;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* Common operations performed on an entity in the context of it's mapping metadata.
@@ -113,20 +107,6 @@ class EntityOperations {
return AdaptibleMappedEntity.of(entity, context, conversionService);
}
/**
* @param source can be {@literal null}.
* @return {@literal true} if the given value is an {@literal array}, {@link Collection} or {@link Iterator}.
* @since 3.2
*/
static boolean isCollectionLike(@Nullable Object source) {
if (source == null) {
return false;
}
return ObjectUtils.isArray(source) || source instanceof Collection || source instanceof Iterator;
}
/**
* @param entityClass should not be null.
* @return the {@link MongoPersistentEntity#getCollection() collection name}.
@@ -782,24 +762,6 @@ class EntityOperations {
* @return
*/
Optional<Collation> getCollation(Query query);
/**
* Derive the applicable {@link CollectionOptions} for the given type.
*
* @return never {@literal null}.
* @since 3.3
*/
CollectionOptions getCollectionOptions();
/**
* Map the fields of a given {@link TimeSeriesOptions} against the target domain type to consider potentially
* annotated field names.
*
* @param options must not be {@literal null}.
* @return never {@literal null}.
* @since 3.3
*/
TimeSeriesOptions mapTimeSeriesOptions(TimeSeriesOptions options);
}
/**
@@ -839,16 +801,6 @@ class EntityOperations {
return query.getCollation();
}
@Override
public CollectionOptions getCollectionOptions() {
return CollectionOptions.empty();
}
@Override
public TimeSeriesOptions mapTimeSeriesOptions(TimeSeriesOptions options) {
return options;
}
}
/**
@@ -886,58 +838,6 @@ class EntityOperations {
return Optional.ofNullable(entity.getCollation());
}
@Override
public CollectionOptions getCollectionOptions() {
CollectionOptions collectionOptions = CollectionOptions.empty();
if (entity.hasCollation()) {
collectionOptions = collectionOptions.collation(entity.getCollation());
}
if (entity.isAnnotationPresent(TimeSeries.class)) {
TimeSeries timeSeries = entity.getRequiredAnnotation(TimeSeries.class);
if (entity.getPersistentProperty(timeSeries.timeField()) == null) {
throw new MappingException(String.format("Time series field '%s' does not exist in type %s",
timeSeries.timeField(), entity.getName()));
}
TimeSeriesOptions options = TimeSeriesOptions.timeSeries(timeSeries.timeField());
if (StringUtils.hasText(timeSeries.metaField())) {
if (entity.getPersistentProperty(timeSeries.metaField()) == null) {
throw new MappingException(
String.format("Meta field '%s' does not exist in type %s", timeSeries.metaField(), entity.getName()));
}
options = options.metaField(timeSeries.metaField());
}
if (!Granularity.DEFAULT.equals(timeSeries.granularity())) {
options = options.granularity(timeSeries.granularity());
}
collectionOptions = collectionOptions.timeSeries(options);
}
return collectionOptions;
}
@Override
public TimeSeriesOptions mapTimeSeriesOptions(TimeSeriesOptions source) {
TimeSeriesOptions target = TimeSeriesOptions.timeSeries(mappedNameOrDefault(source.getTimeField()));
if (StringUtils.hasText(source.getMetaField())) {
target = target.metaField(mappedNameOrDefault(source.getMetaField()));
}
return target.granularity(source.getGranularity());
}
private String mappedNameOrDefault(String name) {
MongoPersistentProperty persistentProperty = entity.getPersistentProperty(name);
return persistentProperty != null ? persistentProperty.getFieldName() : name;
}
}
}

View File

@@ -115,10 +115,6 @@ abstract class IndexConverters {
ops = ops.collation(fromDocument(indexOptions.get("collation", Document.class)));
}
if (indexOptions.containsKey("wildcardProjection")) {
ops.wildcardProjection(indexOptions.get("wildcardProjection", Document.class));
}
return ops;
};
}

View File

@@ -1258,13 +1258,11 @@ public interface MongoOperations extends FluentMongoOperations {
* <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#validation" > Spring's
* Type Conversion"</a> for more details.
* <p/>
* Insert is used to initially store the object into the database. To update an existing object use the save method.
* <p/>
* The {@code objectToSave} must not be collection-like.
* Insert is used to initially store the object into the database. To update an existing object use the save method.
*
* @param objectToSave the object to store in the collection. Must not be {@literal null}.
* @return the inserted object.
* @throws IllegalArgumentException in case the {@code objectToSave} is collection-like.
*/
<T> T insert(T objectToSave);
@@ -1275,13 +1273,10 @@ public interface MongoOperations extends FluentMongoOperations {
* configured otherwise, an instance of {@link MappingMongoConverter} will be used.
* <p/>
* Insert is used to initially store the object into the database. To update an existing object use the save method.
* <p/>
* The {@code objectToSave} must not be collection-like.
*
* @param objectToSave the object to store in the collection. Must not be {@literal null}.
* @param collectionName name of the collection to store the object in. Must not be {@literal null}.
* @return the inserted object.
* @throws IllegalArgumentException in case the {@code objectToSave} is collection-like.
*/
<T> T insert(T objectToSave, String collectionName);
@@ -1324,12 +1319,9 @@ public interface MongoOperations extends FluentMongoOperations {
* property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. See
* <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#validation" > Spring's
* Type Conversion"</a> for more details.
* <p />
* The {@code objectToSave} must not be collection-like.
*
* @param objectToSave the object to store in the collection. Must not be {@literal null}.
* @return the saved object.
* @throws IllegalArgumentException in case the {@code objectToSave} is collection-like.
*/
<T> T save(T objectToSave);
@@ -1345,13 +1337,10 @@ public interface MongoOperations extends FluentMongoOperations {
* property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. See <a
* https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#validation">Spring's Type
* Conversion"</a> for more details.
* <p />
* The {@code objectToSave} must not be collection-like.
*
* @param objectToSave the object to store in the collection. Must not be {@literal null}.
* @param collectionName name of the collection to store the object in. Must not be {@literal null}.
* @return the saved object.
* @throws IllegalArgumentException in case the {@code objectToSave} is collection-like.
*/
<T> T save(T objectToSave, String collectionName);

View File

@@ -28,7 +28,6 @@ import org.bson.Document;
import org.bson.conversions.Bson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
@@ -47,7 +46,6 @@ import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Metric;
import org.springframework.data.mapping.MappingException;
import org.springframework.data.mapping.callback.EntityCallbacks;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.MongoDatabaseFactory;
@@ -56,7 +54,6 @@ import org.springframework.data.mongodb.SessionSynchronization;
import org.springframework.data.mongodb.core.BulkOperations.BulkMode;
import org.springframework.data.mongodb.core.DefaultBulkOperations.BulkOperationContext;
import org.springframework.data.mongodb.core.EntityOperations.AdaptibleEntity;
import org.springframework.data.mongodb.core.QueryOperations.AggregationDefinition;
import org.springframework.data.mongodb.core.QueryOperations.CountContext;
import org.springframework.data.mongodb.core.QueryOperations.DeleteContext;
import org.springframework.data.mongodb.core.QueryOperations.DistinctQueryContext;
@@ -99,12 +96,12 @@ import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.data.mongodb.core.query.UpdateDefinition.ArrayFilter;
import org.springframework.data.mongodb.core.timeseries.Granularity;
import org.springframework.data.mongodb.core.validation.Validator;
import org.springframework.data.mongodb.util.BsonUtils;
import org.springframework.data.projection.SpelAwareProxyProjectionFactory;
import org.springframework.data.util.CloseableIterator;
import org.springframework.data.util.Optionals;
import org.springframework.jca.cci.core.ConnectionCallback;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
@@ -158,13 +155,22 @@ import com.mongodb.client.result.UpdateResult;
* @author Michael J. Simons
* @author Roman Puchkovskiy
* @author Yadhukrishna S Pai
* @author Anton Barkan
* @author Bartłomiej Mazur
*/
public class MongoTemplate implements MongoOperations, ApplicationContextAware, IndexOperationsProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(MongoTemplate.class);
private static final WriteResultChecking DEFAULT_WRITE_RESULT_CHECKING = WriteResultChecking.NONE;
private static final Collection<String> ITERABLE_CLASSES;
static {
Set<String> iterableClasses = new HashSet<>();
iterableClasses.add(List.class.getName());
iterableClasses.add(Collection.class.getName());
iterableClasses.add(Iterator.class.getName());
ITERABLE_CLASSES = Collections.unmodifiableCollection(iterableClasses);
}
private final MongoConverter mongoConverter;
private final MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext;
@@ -598,7 +604,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
* @see org.springframework.data.mongodb.core.MongoOperations#createCollection(java.lang.Class)
*/
public <T> MongoCollection<Document> createCollection(Class<T> entityClass) {
return createCollection(entityClass, operations.forType(entityClass).getCollectionOptions());
return createCollection(entityClass, CollectionOptions.empty());
}
/*
@@ -707,17 +713,12 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
});
}
@Override
public IndexOperations indexOps(String collectionName) {
return indexOps(collectionName, null);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ExecutableInsertOperation#indexOps(java.lang.String)
*/
public IndexOperations indexOps(String collectionName, @Nullable Class<?> type) {
return new DefaultIndexOperations(this, collectionName, type);
public IndexOperations indexOps(String collectionName) {
return new DefaultIndexOperations(this, collectionName, null);
}
/*
@@ -725,7 +726,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
* @see org.springframework.data.mongodb.core.ExecutableInsertOperation#indexOps(java.lang.Class)
*/
public IndexOperations indexOps(Class<?> entityClass) {
return indexOps(getCollectionName(entityClass), entityClass);
return new DefaultIndexOperations(this, getCollectionName(entityClass), entityClass);
}
/*
@@ -974,7 +975,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
for (Document element : results) {
GeoResult<T> geoResult = callback.doWith(element);
aggregate = aggregate.add(BigDecimal.valueOf(geoResult.getDistance().getValue()));
aggregate = aggregate.add(new BigDecimal(geoResult.getDistance().getValue()));
result.add(geoResult);
}
@@ -1174,28 +1175,11 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
return (T) doInsert(collectionName, objectToSave, this.mongoConverter);
}
/**
* Ensure the given {@literal source} is not an {@link java.lang.reflect.Array}, {@link Collection} or
* {@link Iterator}.
*
* @param source can be {@literal null}.
* @deprecated since 3.2. Call {@link #ensureNotCollectionLike(Object)} instead.
*/
protected void ensureNotIterable(@Nullable Object source) {
ensureNotCollectionLike(source);
}
/**
* Ensure the given {@literal source} is not an {@link java.lang.reflect.Array}, {@link Collection} or
* {@link Iterator}.
*
* @param source can be {@literal null}.
* @since 3.2.
*/
protected void ensureNotCollectionLike(@Nullable Object source) {
if (EntityOperations.isCollectionLike(source)) {
throw new IllegalArgumentException("Cannot use a collection here.");
protected void ensureNotIterable(@Nullable Object o) {
if (o != null) {
if (o.getClass().isArray() || ITERABLE_CLASSES.contains(o.getClass().getName())) {
throw new IllegalArgumentException("Cannot use a collection here.");
}
}
}
@@ -1378,7 +1362,6 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
Assert.notNull(objectToSave, "Object to save must not be null!");
Assert.hasText(collectionName, "Collection name must not be null or empty!");
ensureNotCollectionLike(objectToSave);
AdaptibleEntity<T> source = operations.forEntity(objectToSave, mongoConverter.getConversionService());
@@ -2003,7 +1986,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
public <O> AggregationResults<O> aggregate(Aggregation aggregation, Class<?> inputType, Class<O> outputType) {
return aggregate(aggregation, getCollectionName(inputType), outputType,
queryOperations.createAggregation(aggregation, inputType).getAggregationOperationContext());
new TypeBasedAggregationOperationContext(inputType, mappingContext, queryMapper));
}
/* (non-Javadoc)
@@ -2110,13 +2093,9 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
Assert.notNull(aggregation, "Aggregation pipeline must not be null!");
Assert.notNull(outputType, "Output type must not be null!");
return doAggregate(aggregation, collectionName, outputType,
queryOperations.createAggregation(aggregation, context));
}
private <O> AggregationResults<O> doAggregate(Aggregation aggregation, String collectionName, Class<O> outputType,
AggregationDefinition context) {
return doAggregate(aggregation, collectionName, outputType, context.getAggregationOperationContext());
AggregationOperationContext contextToUse = new AggregationUtil(queryMapper, mappingContext)
.prepareAggregationContext(aggregation, context);
return doAggregate(aggregation, collectionName, outputType, contextToUse);
}
@SuppressWarnings("ConstantConditions")
@@ -2204,10 +2183,11 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
Assert.notNull(outputType, "Output type must not be null!");
Assert.isTrue(!aggregation.getOptions().isExplain(), "Can't use explain option with streaming!");
AggregationDefinition aggregationDefinition = queryOperations.createAggregation(aggregation, context);
AggregationUtil aggregationUtil = new AggregationUtil(queryMapper, mappingContext);
AggregationOperationContext rootContext = aggregationUtil.prepareAggregationContext(aggregation, context);
AggregationOptions options = aggregation.getOptions();
List<Document> pipeline = aggregationDefinition.getAggregationPipeline();
List<Document> pipeline = aggregationUtil.createPipeline(aggregation, rootContext);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Streaming aggregation: {} in collection {}", serializeToJsonSafely(pipeline), collectionName);
@@ -2436,20 +2416,6 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
co.validationOptions(options);
}
if (collectionOptions.containsKey("timeseries")) {
Document timeSeries = collectionOptions.get("timeseries", Document.class);
com.mongodb.client.model.TimeSeriesOptions options = new com.mongodb.client.model.TimeSeriesOptions(
timeSeries.getString("timeField"));
if (timeSeries.containsKey("metaField")) {
options.metaField(timeSeries.getString("metaField"));
}
if (timeSeries.containsKey("granularity")) {
options.granularity(TimeSeriesGranularity.valueOf(timeSeries.getString("granularity").toUpperCase()));
}
co.timeSeriesOptions(options);
}
db.createCollection(collectionName, co);
MongoCollection<Document> coll = db.getCollection(collectionName, Document.class);
@@ -2604,19 +2570,6 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
collectionOptions.getValidationOptions().ifPresent(it -> it.getValidator() //
.ifPresent(val -> doc.put("validator", getMappedValidator(val, targetType))));
collectionOptions.getTimeSeriesOptions().map(operations.forType(targetType)::mapTimeSeriesOptions)
.ifPresent(it -> {
Document timeseries = new Document("timeField", it.getTimeField());
if (StringUtils.hasText(it.getMetaField())) {
timeseries.append("metaField", it.getMetaField());
}
if (!Granularity.DEFAULT.equals(it.getGranularity())) {
timeseries.append("granularity", it.getGranularity().name().toLowerCase());
}
doc.put("timeseries", timeseries);
});
}
return doc;
@@ -2780,24 +2733,25 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
* Internal method using callbacks to do queries against the datastore that requires reading a single object from a
* collection of objects. It will take the following steps
* <ol>
* <li>Execute the given {@link CollectionCallback} for a {@link Document}.</li>
* <li>Execute the given {@link ConnectionCallback} for a {@link Document}.</li>
* <li>Apply the given {@link DocumentCallback} to each of the {@link Document}s to obtain the result.</li>
* <ol>
*
* @param <T>
* @param collectionCallback the callback to retrieve the {@link Document} with
* @param documentCallback the {@link DocumentCallback} to transform {@link Document}s into the actual domain type
* @param objectCallback the {@link DocumentCallback} to transform {@link Document}s into the actual domain type
* @param collectionName the collection to be queried
* @return
*/
@Nullable
private <T> T executeFindOneInternal(CollectionCallback<Document> collectionCallback,
DocumentCallback<T> documentCallback, String collectionName) {
DocumentCallback<T> objectCallback, String collectionName) {
try {
Document document = collectionCallback.doInCollection(getAndPrepareCollection(doGetDatabase(), collectionName));
return document != null ? documentCallback.doWith(document) : null;
T result = objectCallback
.doWith(collectionCallback.doInCollection(getAndPrepareCollection(doGetDatabase(), collectionName)));
return result;
} catch (RuntimeException e) {
throw potentiallyConvertRuntimeException(e, exceptionTranslator);
}
@@ -2807,7 +2761,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
* Internal method using callback to do queries against the datastore that requires reading a collection of objects.
* It will take the following steps
* <ol>
* <li>Execute the given {@link CollectionCallback} for a {@link FindIterable}.</li>
* <li>Execute the given {@link ConnectionCallback} for a {@link FindIterable}.</li>
* <li>Prepare that {@link FindIterable} with the given {@link CursorPreparer} (will be skipped if
* {@link CursorPreparer} is {@literal null}</li>
* <li>Iterate over the {@link FindIterable} and applies the given {@link DocumentCallback} to each of the
@@ -2817,27 +2771,36 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
* @param <T>
* @param collectionCallback the callback to retrieve the {@link FindIterable} with
* @param preparer the {@link CursorPreparer} to potentially modify the {@link FindIterable} before iterating over it
* @param documentCallback the {@link DocumentCallback} to transform {@link Document}s into the actual domain type
* @param objectCallback the {@link DocumentCallback} to transform {@link Document}s into the actual domain type
* @param collectionName the collection to be queried
* @return
*/
private <T> List<T> executeFindMultiInternal(CollectionCallback<FindIterable<Document>> collectionCallback,
CursorPreparer preparer, DocumentCallback<T> documentCallback, String collectionName) {
CursorPreparer preparer, DocumentCallback<T> objectCallback, String collectionName) {
try {
try (MongoCursor<Document> cursor = preparer
.initiateFind(getAndPrepareCollection(doGetDatabase(), collectionName), collectionCallback::doInCollection)
.iterator()) {
MongoCursor<Document> cursor = null;
try {
cursor = preparer
.initiateFind(getAndPrepareCollection(doGetDatabase(), collectionName), collectionCallback::doInCollection)
.iterator();
List<T> result = new ArrayList<>();
while (cursor.hasNext()) {
Document object = cursor.next();
result.add(documentCallback.doWith(object));
result.add(objectCallback.doWith(object));
}
return result;
} finally {
if (cursor != null) {
cursor.close();
}
}
} catch (RuntimeException e) {
throw potentiallyConvertRuntimeException(e, exceptionTranslator);
@@ -2847,12 +2810,23 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
private void executeQueryInternal(CollectionCallback<FindIterable<Document>> collectionCallback,
CursorPreparer preparer, DocumentCallbackHandler callbackHandler, String collectionName) {
try (MongoCursor<Document> cursor = preparer
.initiateFind(getAndPrepareCollection(doGetDatabase(), collectionName), collectionCallback::doInCollection)
.iterator()) {
try {
while (cursor.hasNext()) {
callbackHandler.processDocument(cursor.next());
MongoCursor<Document> cursor = null;
try {
cursor = preparer
.initiateFind(getAndPrepareCollection(doGetDatabase(), collectionName), collectionCallback::doInCollection)
.iterator();
while (cursor.hasNext()) {
callbackHandler.processDocument(cursor.next());
}
} finally {
if (cursor != null) {
cursor.close();
}
}
} catch (RuntimeException e) {
throw potentiallyConvertRuntimeException(e, exceptionTranslator);
@@ -3151,7 +3125,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
interface DocumentCallback<T> {
T doWith(Document object);
@Nullable
T doWith(@Nullable Document object);
}
/**
@@ -3175,19 +3150,22 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
this.collectionName = collectionName;
}
public T doWith(Document document) {
@Nullable
public T doWith(@Nullable Document document) {
maybeEmitEvent(new AfterLoadEvent<>(document, type, collectionName));
T entity = reader.read(type, document);
T source = null;
if (entity == null) {
throw new MappingException(String.format("EntityReader %s returned null", reader));
if (document != null) {
maybeEmitEvent(new AfterLoadEvent<>(document, type, collectionName));
source = reader.read(type, document);
}
maybeEmitEvent(new AfterConvertEvent<>(document, entity, collectionName));
entity = maybeCallAfterConvert(entity, document, collectionName);
if (source != null) {
maybeEmitEvent(new AfterConvertEvent<>(document, source, collectionName));
source = maybeCallAfterConvert(source, document, collectionName);
}
return entity;
return source;
}
}
@@ -3220,7 +3198,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
* @see org.springframework.data.mongodb.core.MongoTemplate.DocumentCallback#doWith(org.bson.Document)
*/
@SuppressWarnings("unchecked")
public T doWith(Document document) {
@Nullable
public T doWith(@Nullable Document document) {
if (document == null) {
return null;
@@ -3231,16 +3210,15 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
maybeEmitEvent(new AfterLoadEvent<>(document, targetType, collectionName));
Object entity = reader.read(typeToRead, document);
Object source = reader.read(typeToRead, document);
Object result = targetType.isInterface() ? projectionFactory.createProjection(targetType, source) : source;
if (entity == null) {
throw new MappingException(String.format("EntityReader %s returned null", reader));
if (result != null) {
maybeEmitEvent(new AfterConvertEvent<>(document, result, collectionName));
result = maybeCallAfterConvert(result, document, collectionName);
}
Object result = targetType.isInterface() ? projectionFactory.createProjection(targetType, entity) : entity;
maybeEmitEvent(new AfterConvertEvent<>(document, result, collectionName));
return (T) maybeCallAfterConvert(result, document, collectionName);
return (T) result;
}
}
@@ -3310,10 +3288,6 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
cursorToUse = cursorToUse.batchSize(meta.getCursorBatchSize());
}
if (meta.getAllowDiskUse() != null) {
cursorToUse = cursorToUse.allowDiskUse(meta.getAllowDiskUse());
}
for (Meta.CursorOption option : meta.getFlags()) {
switch (option) {
@@ -3377,7 +3351,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
this.metric = metric;
}
public GeoResult<T> doWith(Document object) {
@Nullable
public GeoResult<T> doWith(@Nullable Document object) {
double distance = Double.NaN;
if (object.containsKey(distanceField)) {
@@ -3404,6 +3379,10 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
/**
* Creates a new {@link CloseableIterableCursorAdapter} backed by the given {@link MongoCollection}.
*
* @param cursor
* @param exceptionTranslator
* @param objectReadCallback
*/
CloseableIterableCursorAdapter(MongoIterable<Document> cursor, PersistenceExceptionTranslator exceptionTranslator,
DocumentCallback<T> objectReadCallback) {
@@ -3447,7 +3426,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware,
try {
Document item = cursor.next();
return objectReadCallback.doWith(item);
T converted = objectReadCallback.doWith(item);
return converted;
} catch (RuntimeException ex) {
throw potentiallyConvertRuntimeException(ex, exceptionTranslator);
}

View File

@@ -17,7 +17,6 @@ package org.springframework.data.mongodb.core;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -32,17 +31,11 @@ import org.springframework.data.mapping.PropertyPath;
import org.springframework.data.mapping.PropertyReferenceException;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.CodecRegistryProvider;
import org.springframework.data.mongodb.MongoExpression;
import org.springframework.data.mongodb.core.MappedDocument.MappedUpdate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationExpression;
import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext;
import org.springframework.data.mongodb.core.aggregation.AggregationOptions;
import org.springframework.data.mongodb.core.aggregation.AggregationPipeline;
import org.springframework.data.mongodb.core.aggregation.AggregationUpdate;
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.convert.UpdateMapper;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
@@ -55,7 +48,6 @@ import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.data.mongodb.core.query.UpdateDefinition.ArrayFilter;
import org.springframework.data.mongodb.util.BsonUtils;
import org.springframework.data.projection.ProjectionFactory;
import org.springframework.data.util.Lazy;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
@@ -202,34 +194,9 @@ class QueryOperations {
return new DeleteContext(query, false);
}
/**
* Create a new {@link AggregationDefinition} for the given {@link Aggregation}.
*
* @param aggregation must not be {@literal null}.
* @param inputType fallback mapping type in case of untyped aggregation. Can be {@literal null}.
* @return new instance of {@link AggregationDefinition}.
* @since 3.2
*/
AggregationDefinition createAggregation(Aggregation aggregation, @Nullable Class<?> inputType) {
return new AggregationDefinition(aggregation, inputType);
}
/**
* Create a new {@link AggregationDefinition} for the given {@link Aggregation}.
*
* @param aggregation must not be {@literal null}.
* @param aggregationOperationContext the {@link AggregationOperationContext} to use. Can be {@literal null}.
* @return new instance of {@link AggregationDefinition}.
* @since 3.2
*/
AggregationDefinition createAggregation(Aggregation aggregation,
@Nullable AggregationOperationContext aggregationOperationContext) {
return new AggregationDefinition(aggregation, aggregationOperationContext);
}
/**
* {@link QueryContext} encapsulates common tasks required to convert a {@link Query} into its MongoDB document
* representation, mapping field names, as well as determining and applying {@link Collation collations}.
* representation, mapping fieldnames, as well as determinging and applying {@link Collation collations}.
*
* @author Christoph Strobl
*/
@@ -238,7 +205,7 @@ class QueryOperations {
private final Query query;
/**
* Create new a {@link QueryContext} instance from the given {@literal query} (can be either a {@link Query} or a
* Create new a {@link QueryContext} instance from the given {@literal query} (can be eihter a {@link Query} or a
* plain {@link Document}.
*
* @param query can be {@literal null}.
@@ -291,21 +258,7 @@ class QueryOperations {
Document getMappedFields(@Nullable MongoPersistentEntity<?> entity, Class<?> targetType,
ProjectionFactory projectionFactory) {
Document fields = new Document();
for (Entry<String, Object> entry : query.getFieldsObject().entrySet()) {
if (entry.getValue() instanceof MongoExpression) {
AggregationOperationContext ctx = entity == null ? Aggregation.DEFAULT_CONTEXT
: new RelaxedTypeBasedAggregationOperationContext(entity.getType(), mappingContext, queryMapper);
fields.put(entry.getKey(), AggregationExpression.from((MongoExpression) entry.getValue()).toDocument(ctx));
} else {
fields.put(entry.getKey(), entry.getValue());
}
}
Document fields = query.getFieldsObject();
Document mappedFields = fields;
if (entity == null) {
@@ -322,7 +275,7 @@ class QueryOperations {
mappingContext.getRequiredPersistentEntity(targetType));
}
if (entity.hasTextScoreProperty() && !query.getQueryObject().containsKey("$text")) {
if (entity != null && entity.hasTextScoreProperty() && !query.getQueryObject().containsKey("$text")) {
mappedFields.remove(entity.getTextScoreProperty().getFieldName());
}
@@ -388,8 +341,7 @@ class QueryOperations {
}
@Override
Document getMappedFields(@Nullable MongoPersistentEntity<?> entity, Class<?> targetType,
ProjectionFactory projectionFactory) {
Document getMappedFields(@Nullable MongoPersistentEntity<?> entity, Class<?> targetType, ProjectionFactory projectionFactory) {
return getMappedFields(entity);
}
@@ -758,8 +710,7 @@ class QueryOperations {
Class<?> type = domainType != null ? domainType : Object.class;
AggregationOperationContext context = new RelaxedTypeBasedAggregationOperationContext(type, mappingContext,
queryMapper);
AggregationOperationContext context = new RelaxedTypeBasedAggregationOperationContext(type, mappingContext, queryMapper);
return aggregationUtil.createPipeline((AggregationUpdate) update, context);
}
@@ -809,105 +760,4 @@ class QueryOperations {
return multi;
}
}
/**
* A value object that encapsulates common tasks required when running {@literal aggregations}.
*
* @since 3.2
*/
class AggregationDefinition {
private final Aggregation aggregation;
private final Lazy<AggregationOperationContext> aggregationOperationContext;
private final Lazy<List<Document>> pipeline;
private final @Nullable Class<?> inputType;
/**
* Creates new instance of {@link AggregationDefinition} extracting the input type from either the
* {@link org.springframework.data.mongodb.core.aggregation.Aggregation} in case of a {@link TypedAggregation} or
* the given {@literal aggregationOperationContext} if present. <br />
* Creates a new {@link AggregationOperationContext} if none given, based on the {@link Aggregation} input type and
* the desired {@link AggregationOptions#getDomainTypeMapping() domain type mapping}. <br />
* Pipelines are mapped on first access of {@link #getAggregationPipeline()} and cached for reuse.
*
* @param aggregation the source aggregation.
* @param aggregationOperationContext can be {@literal null}.
*/
AggregationDefinition(Aggregation aggregation, @Nullable AggregationOperationContext aggregationOperationContext) {
this.aggregation = aggregation;
if (aggregation instanceof TypedAggregation) {
this.inputType = ((TypedAggregation<?>) aggregation).getInputType();
} else if (aggregationOperationContext instanceof TypeBasedAggregationOperationContext) {
this.inputType = ((TypeBasedAggregationOperationContext) aggregationOperationContext).getType();
} else {
this.inputType = null;
}
this.aggregationOperationContext = Lazy.of(() -> aggregationOperationContext != null ? aggregationOperationContext
: aggregationUtil.createAggregationContext(aggregation, getInputType()));
this.pipeline = Lazy.of(() -> aggregationUtil.createPipeline(this.aggregation, getAggregationOperationContext()));
}
/**
* Creates new instance of {@link AggregationDefinition} extracting the input type from either the
* {@link org.springframework.data.mongodb.core.aggregation.Aggregation} in case of a {@link TypedAggregation} or
* the given {@literal aggregationOperationContext} if present. <br />
* Creates a new {@link AggregationOperationContext} based on the {@link Aggregation} input type and the desired
* {@link AggregationOptions#getDomainTypeMapping() domain type mapping}. <br />
* Pipelines are mapped on first access of {@link #getAggregationPipeline()} and cached for reuse.
*
* @param aggregation the source aggregation.
* @param inputType can be {@literal null}.
*/
AggregationDefinition(Aggregation aggregation, @Nullable Class<?> inputType) {
this.aggregation = aggregation;
if (aggregation instanceof TypedAggregation) {
this.inputType = ((TypedAggregation<?>) aggregation).getInputType();
} else {
this.inputType = inputType;
}
this.aggregationOperationContext = Lazy
.of(() -> aggregationUtil.createAggregationContext(aggregation, getInputType()));
this.pipeline = Lazy.of(() -> aggregationUtil.createPipeline(this.aggregation, getAggregationOperationContext()));
}
/**
* Obtain the already mapped pipeline.
*
* @return never {@literal null}.
*/
List<Document> getAggregationPipeline() {
return pipeline.get();
}
/**
* @return {@literal true} if the last aggregation stage is either {@literal $out} or {@literal $merge}.
* @see AggregationPipeline#isOutOrMerge()
*/
boolean isOutOrMerge() {
return aggregation.getPipeline().isOutOrMerge();
}
/**
* Obtain the {@link AggregationOperationContext} used for mapping the pipeline.
*
* @return never {@literal null}.
*/
AggregationOperationContext getAggregationOperationContext() {
return aggregationOperationContext.get();
}
/**
* @return the input type to map the pipeline against. Can be {@literal null}.
*/
@Nullable
Class<?> getInputType() {
return inputType;
}
}
}

View File

@@ -1038,13 +1038,11 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
* <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#validation" > Spring's
* Type Conversion"</a> for more details.
* <p/>
* <p/>
* Insert is used to initially store the object into the database. To update an existing object use the save method.
* <p />
* The {@code objectToSave} must not be collection-like.
*
* @param objectToSave the object to store in the collection. Must not be {@literal null}.
* @return the inserted object.
* @throws IllegalArgumentException in case the {@code objectToSave} is collection-like.
*/
<T> Mono<T> insert(T objectToSave);
@@ -1055,13 +1053,10 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
* configured otherwise, an instance of {@link MappingMongoConverter} will be used.
* <p/>
* Insert is used to initially store the object into the database. To update an existing object use the save method.
* <p />
* The {@code objectToSave} must not be collection-like.
*
* @param objectToSave the object to store in the collection. Must not be {@literal null}.
* @param collectionName name of the collection to store the object in. Must not be {@literal null}.
* @return the inserted object.
* @throws IllegalArgumentException in case the {@code objectToSave} is collection-like.
*/
<T> Mono<T> insert(T objectToSave, String collectionName);
@@ -1103,6 +1098,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
* <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#validation" > Spring's
* Type Conversion"</a> for more details.
* <p/>
* <p/>
* Insert is used to initially store the object into the database. To update an existing object use the save method.
*
* @param objectToSave the object to store in the collection. Must not be {@literal null}.
@@ -1149,12 +1145,9 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
* property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. See
* <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#validation" > Spring's
* Type Conversion"</a> for more details.
* <p />
* The {@code objectToSave} must not be collection-like.
*
* @param objectToSave the object to store in the collection. Must not be {@literal null}.
* @return the saved object.
* @throws IllegalArgumentException in case the {@code objectToSave} is collection-like.
*/
<T> Mono<T> save(T objectToSave);
@@ -1174,7 +1167,6 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations {
* @param objectToSave the object to store in the collection. Must not be {@literal null}.
* @param collectionName name of the collection to store the object in. Must not be {@literal null}.
* @return the saved object.
* @throws IllegalArgumentException in case the {@code objectToSave} is collection-like.
*/
<T> Mono<T> save(T objectToSave, String collectionName);

View File

@@ -17,20 +17,13 @@ package org.springframework.data.mongodb.core;
import static org.springframework.data.mongodb.core.query.SerializationUtils.*;
import org.springframework.data.mongodb.core.aggregation.RelaxedTypeBasedAggregationOperationContext;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
@@ -60,7 +53,6 @@ import org.springframework.data.convert.EntityReader;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.Metric;
import org.springframework.data.mapping.MappingException;
import org.springframework.data.mapping.PersistentEntity;
import org.springframework.data.mapping.callback.ReactiveEntityCallbacks;
import org.springframework.data.mapping.context.MappingContext;
@@ -70,7 +62,6 @@ import org.springframework.data.mongodb.ReactiveMongoDatabaseFactory;
import org.springframework.data.mongodb.ReactiveMongoDatabaseUtils;
import org.springframework.data.mongodb.SessionSynchronization;
import org.springframework.data.mongodb.core.EntityOperations.AdaptibleEntity;
import org.springframework.data.mongodb.core.QueryOperations.AggregationDefinition;
import org.springframework.data.mongodb.core.QueryOperations.CountContext;
import org.springframework.data.mongodb.core.QueryOperations.DeleteContext;
import org.springframework.data.mongodb.core.QueryOperations.DistinctQueryContext;
@@ -80,7 +71,6 @@ import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext;
import org.springframework.data.mongodb.core.aggregation.AggregationOptions;
import org.springframework.data.mongodb.core.aggregation.PrefixingDelegatingAggregationOperationContext;
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.DbRefResolver;
@@ -110,7 +100,6 @@ import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.data.mongodb.core.query.UpdateDefinition.ArrayFilter;
import org.springframework.data.mongodb.core.timeseries.Granularity;
import org.springframework.data.mongodb.core.validation.Validator;
import org.springframework.data.mongodb.util.BsonUtils;
import org.springframework.data.projection.SpelAwareProxyProjectionFactory;
@@ -167,6 +156,18 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
private static final Logger LOGGER = LoggerFactory.getLogger(ReactiveMongoTemplate.class);
private static final WriteResultChecking DEFAULT_WRITE_RESULT_CHECKING = WriteResultChecking.NONE;
private static final Collection<Class<?>> ITERABLE_CLASSES;
static {
Set<Class<?>> iterableClasses = new HashSet<>();
iterableClasses.add(List.class);
iterableClasses.add(Collection.class);
iterableClasses.add(Iterator.class);
iterableClasses.add(Publisher.class);
ITERABLE_CLASSES = Collections.unmodifiableCollection(iterableClasses);
}
private final MongoConverter mongoConverter;
private final MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext;
@@ -666,7 +667,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
* @see org.springframework.data.mongodb.core.ReactiveMongoOperations#createCollection(java.lang.Class)
*/
public <T> Mono<MongoCollection<Document>> createCollection(Class<T> entityClass) {
return createCollection(entityClass, operations.forType(entityClass).getCollectionOptions());
return createCollection(entityClass, CollectionOptions.empty());
}
/*
@@ -945,7 +946,9 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
Assert.notNull(aggregation, "Aggregation pipeline must not be null!");
return doAggregate(aggregation, inputCollectionName, aggregation.getInputType(), outputType);
AggregationOperationContext context = new TypeBasedAggregationOperationContext(aggregation.getInputType(),
mappingContext, queryMapper);
return aggregate(aggregation, inputCollectionName, outputType, context);
}
/*
@@ -963,7 +966,9 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
*/
@Override
public <O> Flux<O> aggregate(Aggregation aggregation, Class<?> inputType, Class<O> outputType) {
return doAggregate(aggregation, getCollectionName(inputType), inputType, outputType);
return aggregate(aggregation, getCollectionName(inputType), outputType,
new TypeBasedAggregationOperationContext(inputType, mappingContext, queryMapper));
}
/*
@@ -972,34 +977,45 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
*/
@Override
public <O> Flux<O> aggregate(Aggregation aggregation, String collectionName, Class<O> outputType) {
return doAggregate(aggregation, collectionName, null, outputType);
return aggregate(aggregation, collectionName, outputType, null);
}
protected <O> Flux<O> doAggregate(Aggregation aggregation, String collectionName, @Nullable Class<?> inputType,
Class<O> outputType) {
/**
* @param aggregation must not be {@literal null}.
* @param collectionName must not be {@literal null}.
* @param outputType must not be {@literal null}.
* @param context can be {@literal null} and will be defaulted to {@link Aggregation#DEFAULT_CONTEXT}.
* @return never {@literal null}.
*/
protected <O> Flux<O> aggregate(Aggregation aggregation, String collectionName, Class<O> outputType,
@Nullable AggregationOperationContext context) {
Assert.notNull(aggregation, "Aggregation pipeline must not be null!");
Assert.hasText(collectionName, "Collection name must not be null or empty!");
Assert.notNull(outputType, "Output type must not be null!");
AggregationUtil aggregationUtil = new AggregationUtil(queryMapper, mappingContext);
AggregationOperationContext rootContext = aggregationUtil.prepareAggregationContext(aggregation, context);
AggregationOptions options = aggregation.getOptions();
List<Document> pipeline = aggregationUtil.createPipeline(aggregation, rootContext);
Assert.isTrue(!options.isExplain(), "Cannot use explain option with streaming!");
AggregationDefinition ctx = queryOperations.createAggregation(aggregation, inputType);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Streaming aggregation: {} in collection {}", serializeToJsonSafely(ctx.getAggregationPipeline()),
collectionName);
LOGGER.debug("Streaming aggregation: {} in collection {}", serializeToJsonSafely(pipeline), collectionName);
}
ReadDocumentCallback<O> readCallback = new ReadDocumentCallback<>(mongoConverter, outputType, collectionName);
return execute(collectionName, collection -> aggregateAndMap(collection, ctx.getAggregationPipeline(),
ctx.isOutOrMerge(), options, readCallback, ctx.getInputType()));
return execute(collectionName,
collection -> aggregateAndMap(collection, pipeline, aggregation.getPipeline().isOutOrMerge(), options,
readCallback,
aggregation instanceof TypedAggregation ? ((TypedAggregation<?>) aggregation).getInputType() : null));
}
private <O> Flux<O> aggregateAndMap(MongoCollection<Document> collection, List<Document> pipeline,
boolean isOutOrMerge, AggregationOptions options, ReadDocumentCallback<O> readCallback,
@Nullable Class<?> inputType) {
boolean isOutOrMerge,
AggregationOptions options, ReadDocumentCallback<O> readCallback, @Nullable Class<?> inputType) {
AggregatePublisher<Document> cursor = collection.aggregate(pipeline, Document.class)
.allowDiskUse(options.isAllowDiskUse());
@@ -2506,20 +2522,6 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
result.validationOptions(validationOptions);
});
collectionOptions.getTimeSeriesOptions().map(operations.forType(entityType)::mapTimeSeriesOptions).ifPresent(it -> {
TimeSeriesOptions options = new TimeSeriesOptions(it.getTimeField());
if (StringUtils.hasText(it.getMetaField())) {
options.metaField(it.getMetaField());
}
if (!Granularity.DEFAULT.equals(it.getGranularity())) {
options.granularity(TimeSeriesGranularity.valueOf(it.getGranularity().name().toUpperCase()));
}
result.timeSeriesOptions(options);
});
return result;
}
@@ -2680,27 +2682,13 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
}
}
/**
* Ensure the given {@literal source} is not an {@link java.lang.reflect.Array}, {@link Collection} or
* {@link Iterator}.
*
* @param source can be {@literal null}.
* @deprecated since 3.2. Call {@link #ensureNotCollectionLike(Object)} instead.
*/
protected void ensureNotIterable(@Nullable Object source) {
ensureNotCollectionLike(source);
}
protected void ensureNotIterable(Object o) {
/**
* Ensure the given {@literal source} is not an {@link java.lang.reflect.Array}, {@link Collection} or
* {@link Iterator}.
*
* @param source can be {@literal null}.
* @since 3.2.
*/
protected void ensureNotCollectionLike(@Nullable Object source) {
boolean isIterable = o.getClass().isArray()
|| ITERABLE_CLASSES.stream().anyMatch(iterableClass -> iterableClass.isAssignableFrom(o.getClass())
|| o.getClass().getName().equals(iterableClass.getName()));
if (EntityOperations.isCollectionLike(source) || source instanceof Publisher) {
if (isIterable) {
throw new IllegalArgumentException("Cannot use a collection here.");
}
}
@@ -3177,14 +3165,13 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
maybeEmitEvent(new AfterLoadEvent<>(document, type, collectionName));
T entity = reader.read(type, document);
if (entity == null) {
throw new MappingException(String.format("EntityReader %s returned null", reader));
T source = reader.read(type, document);
if (source != null) {
maybeEmitEvent(new AfterConvertEvent<>(document, source, collectionName));
return maybeCallAfterConvert(source, document, collectionName);
}
maybeEmitEvent(new AfterConvertEvent<>(document, entity, collectionName));
return maybeCallAfterConvert(entity, document, collectionName);
return Mono.empty();
}
}
@@ -3222,17 +3209,16 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
maybeEmitEvent(new AfterLoadEvent<>(document, typeToRead, collectionName));
Object entity = reader.read(typeToRead, document);
if (entity == null) {
throw new MappingException(String.format("EntityReader %s returned null", reader));
}
Object result = targetType.isInterface() ? projectionFactory.createProjection(targetType, entity) : entity;
Object source = reader.read(typeToRead, document);
Object result = targetType.isInterface() ? projectionFactory.createProjection(targetType, source) : source;
T castEntity = (T) result;
maybeEmitEvent(new AfterConvertEvent<>(document, castEntity, collectionName));
return maybeCallAfterConvert(castEntity, document, collectionName);
if (castEntity != null) {
maybeEmitEvent(new AfterConvertEvent<>(document, castEntity, collectionName));
return maybeCallAfterConvert(castEntity, document, collectionName);
}
return Mono.empty();
}
}
@@ -3351,10 +3337,6 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati
if (meta.getCursorBatchSize() != null) {
findPublisherToUse = findPublisherToUse.batchSize(meta.getCursorBatchSize());
}
if (meta.getAllowDiskUse() != null) {
findPublisherToUse = findPublisherToUse.allowDiskUse(meta.getAllowDiskUse());
}
}
} catch (RuntimeException e) {

View File

@@ -16,7 +16,6 @@
package org.springframework.data.mongodb.core.aggregation;
import org.bson.Document;
import org.springframework.data.mongodb.MongoExpression;
/**
* An {@link AggregationExpression} can be used with field expressions in aggregation pipeline stages like
@@ -26,37 +25,7 @@ import org.springframework.data.mongodb.MongoExpression;
* @author Oliver Gierke
* @author Christoph Strobl
*/
public interface AggregationExpression extends MongoExpression {
/**
* Create an {@link AggregationExpression} out of a given {@link MongoExpression} to ensure the resulting
* {@link MongoExpression#toDocument() Document} is mapped against the {@link AggregationOperationContext}. <br />
* If the given expression is already an {@link AggregationExpression} the very same instance is returned.
*
* @param expression must not be {@literal null}.
* @return never {@literal null}.
* @since 3.2
*/
static AggregationExpression from(MongoExpression expression) {
if (expression instanceof AggregationExpression) {
return AggregationExpression.class.cast(expression);
}
return (context) -> context.getMappedObject(expression.toDocument());
}
/**
* Obtain the as is (unmapped) representation of the {@link AggregationExpression}. Use
* {@link #toDocument(AggregationOperationContext)} with a matching {@link AggregationOperationContext context} to
* engage domain type mapping including field name resolution.
*
* @see org.springframework.data.mongodb.MongoExpression#toDocument()
*/
@Override
default Document toDocument() {
return toDocument(Aggregation.DEFAULT_CONTEXT);
}
public interface AggregationExpression {
/**
* Turns the {@link AggregationExpression} into a {@link Document} within the given

View File

@@ -56,7 +56,6 @@ public class AggregationOptions {
private final Optional<Document> hint;
private Duration maxTime = Duration.ZERO;
private ResultOptions resultOptions = ResultOptions.READ;
private DomainTypeMapping domainTypeMapping = DomainTypeMapping.RELAXED;
/**
* Creates a new {@link AggregationOptions}.
@@ -262,14 +261,6 @@ public class AggregationOptions {
return ResultOptions.SKIP.equals(resultOptions);
}
/**
* @return the domain type mapping strategy do apply. Never {@literal null}.
* @since 3.2
*/
public DomainTypeMapping getDomainTypeMapping() {
return domainTypeMapping;
}
/**
* Returns a new potentially adjusted copy for the given {@code aggregationCommandObject} with the configuration
* applied.
@@ -367,7 +358,6 @@ public class AggregationOptions {
private @Nullable Document hint;
private @Nullable Duration maxTime;
private @Nullable ResultOptions resultOptions;
private @Nullable DomainTypeMapping domainTypeMapping;
/**
* Defines whether to off-load intensive sort-operations to disk.
@@ -485,44 +475,6 @@ public class AggregationOptions {
return this;
}
/**
* Apply a strict domain type mapping considering {@link org.springframework.data.mongodb.core.mapping.Field}
* annotations throwing errors for non-existent, but referenced fields.
*
* @return this.
* @since 3.2
*/
public Builder strictMapping() {
this.domainTypeMapping = DomainTypeMapping.STRICT;
return this;
}
/**
* Apply a relaxed domain type mapping considering {@link org.springframework.data.mongodb.core.mapping.Field}
* annotations using the user provided name if a referenced field does not exist.
*
* @return this.
* @since 3.2
*/
public Builder relaxedMapping() {
this.domainTypeMapping = DomainTypeMapping.RELAXED;
return this;
}
/**
* Apply no domain type mapping at all taking the pipeline as-is.
*
* @return this.
* @since 3.2
*/
public Builder noMapping() {
this.domainTypeMapping = DomainTypeMapping.NONE;
return this;
}
/**
* Returns a new {@link AggregationOptions} instance with the given configuration.
*
@@ -537,9 +489,6 @@ public class AggregationOptions {
if (resultOptions != null) {
options.resultOptions = resultOptions;
}
if (domainTypeMapping != null) {
options.domainTypeMapping = domainTypeMapping;
}
return options;
}
@@ -559,27 +508,4 @@ public class AggregationOptions {
*/
READ;
}
/**
* Aggregation pipeline Domain type mappings supported by the mapping layer.
*
* @since 3.2
*/
public enum DomainTypeMapping {
/**
* Mapping throws errors for non-existent, but referenced fields.
*/
STRICT,
/**
* Fields that do not exist in the model are treated as-is.
*/
RELAXED,
/**
* Do not attempt to map fields against the model and treat the entire pipeline as-is.
*/
NONE
}
}

View File

@@ -1835,7 +1835,7 @@ public class DateOperators {
* @param millisecond must not be {@literal null}.
* @return new instance.
* @throws IllegalArgumentException if given {@literal millisecond} is {@literal null}
* @deprecated since 3.2, use {@link #millisecond(Object)} instead.
* @deprecated since 3.1.3, use {@link #millisecond(Object)} instead.
*/
@Deprecated
default T milliseconds(Object millisecond) {
@@ -1849,7 +1849,7 @@ public class DateOperators {
* @param millisecond must not be {@literal null}.
* @return new instance.
* @throws IllegalArgumentException if given {@literal millisecond} is {@literal null}
* @since 3.2
* @since 3.1.3
*/
T millisecond(Object millisecond);
@@ -1859,7 +1859,7 @@ public class DateOperators {
* @param fieldReference must not be {@literal null}.
* @return new instance.
* @throws IllegalArgumentException if given {@literal fieldReference} is {@literal null}.
* @deprecated since 3.2,use {@link #millisecondOf(String)} instead.
* @deprecated since 3.1.3,use {@link #millisecondOf(String)} instead.
*/
@Deprecated
default T millisecondsOf(String fieldReference) {
@@ -1872,7 +1872,7 @@ public class DateOperators {
* @param fieldReference must not be {@literal null}.
* @return new instance.
* @throws IllegalArgumentException if given {@literal fieldReference} is {@literal null}.
* @since 3.2
* @since 3.1.3
*/
default T millisecondOf(String fieldReference) {
return milliseconds(Fields.field(fieldReference));
@@ -1884,7 +1884,7 @@ public class DateOperators {
* @param expression must not be {@literal null}.
* @return new instance.
* @throws IllegalArgumentException if given {@literal expression} is {@literal null}.
* @deprecated since 3.2, use {@link #millisecondOf(AggregationExpression)} instead.
* @deprecated since 3.1.3, use {@link #millisecondOf(AggregationExpression)} instead.
*/
@Deprecated
default T millisecondsOf(AggregationExpression expression) {
@@ -1897,7 +1897,7 @@ public class DateOperators {
* @param expression must not be {@literal null}.
* @return new instance.
* @throws IllegalArgumentException if given {@literal expression} is {@literal null}.
* @since 3.2
* @since 3.1.3
*/
default T millisecondOf(AggregationExpression expression) {
return milliseconds(expression);

View File

@@ -23,7 +23,6 @@ import java.util.List;
import org.bson.Document;
import org.springframework.data.mongodb.core.aggregation.ExposedFields.ExposedField;
import org.springframework.data.mongodb.core.aggregation.ExposedFields.FieldReference;
import org.springframework.data.mongodb.core.aggregation.ScriptOperators.Accumulator;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
@@ -376,17 +375,6 @@ public class GroupOperation implements FieldsExposingAggregationOperation {
return newBuilder(GroupOps.STD_DEV_POP, null, expr);
}
/**
* Generates an {@link GroupOperationBuilder} for an {@code $accumulator}-expression.
*
* @param accumulator must not be {@literal null}.
* @return never {@literal null}.
* @since 3.2
*/
public GroupOperationBuilder accumulate(Accumulator accumulator) {
return new GroupOperationBuilder(this, new Operation(accumulator));
}
private GroupOperationBuilder newBuilder(Keyword keyword, @Nullable String reference, @Nullable Object value) {
return new GroupOperationBuilder(this, new Operation(keyword, null, reference, value));
}
@@ -477,16 +465,12 @@ public class GroupOperation implements FieldsExposingAggregationOperation {
static class Operation implements AggregationOperation {
private final @Nullable Keyword op;
private final Keyword op;
private final @Nullable String key;
private final @Nullable String reference;
private final @Nullable Object value;
Operation(AggregationExpression expression) {
this(null, null, null, expression);
}
public Operation(@Nullable Keyword op, @Nullable String key, @Nullable String reference, @Nullable Object value) {
public Operation(Keyword op, @Nullable String key, @Nullable String reference, @Nullable Object value) {
this.op = op;
this.key = key;
@@ -503,12 +487,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation {
}
public Document toDocument(AggregationOperationContext context) {
Object value = getValue(context);
if(op == null && value instanceof Document) {
return new Document(key, value);
}
return new Document(key, new Document(op.toString(), value));
return new Document(key, new Document(op.toString(), getValue(context)));
}
public Object getValue(AggregationOperationContext context) {

View File

@@ -15,7 +15,6 @@
*/
package org.springframework.data.mongodb.core.aggregation;
import org.springframework.data.mapping.MappingException;
import org.springframework.data.mapping.context.InvalidPersistentPropertyPath;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.core.aggregation.ExposedFields.DirectFieldReference;
@@ -56,7 +55,7 @@ public class RelaxedTypeBasedAggregationOperationContext extends TypeBasedAggreg
try {
return super.getReferenceFor(field);
} catch (MappingException e) {
} catch (InvalidPersistentPropertyPath e) {
return new DirectFieldReference(new ExposedField(field, true));
}
}

View File

@@ -166,8 +166,4 @@ public class TypeBasedAggregationOperationContext implements AggregationOperatio
return new DirectFieldReference(new ExposedField(mappedField, true));
}
public Class<?> getType() {
return type;
}
}

View File

@@ -35,7 +35,7 @@ import com.mongodb.DBRef;
* @author Mark Paluch
* @since 1.4
*/
public interface DbRefResolver extends ReferenceResolver {
public interface DbRefResolver {
/**
* Resolves the given {@link DBRef} into an object of the given {@link MongoPersistentProperty}'s type. The method

View File

@@ -15,6 +15,13 @@
*/
package org.springframework.data.mongodb.core.convert;
import static org.springframework.util.ReflectionUtils.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -22,18 +29,28 @@ import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.Factory;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.data.mongodb.ClientSessionException;
import org.springframework.data.mongodb.LazyLoadingException;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.MongoDatabaseUtils;
import org.springframework.data.mongodb.core.convert.ReferenceLoader.DocumentReferenceQuery;
import org.springframework.data.mongodb.core.mapping.BasicMongoPersistentProperty;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.lang.Nullable;
import org.springframework.objenesis.ObjenesisStd;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import com.mongodb.DBRef;
@@ -50,11 +67,13 @@ import com.mongodb.client.model.Filters;
* @author Mark Paluch
* @since 1.4
*/
public class DefaultDbRefResolver extends DefaultReferenceResolver implements DbRefResolver, ReferenceResolver {
public class DefaultDbRefResolver implements DbRefResolver {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultDbRefResolver.class);
private final MongoDatabaseFactory mongoDbFactory;
private final PersistenceExceptionTranslator exceptionTranslator;
private final ObjenesisStd objenesis;
/**
* Creates a new {@link DefaultDbRefResolver} with the given {@link MongoDatabaseFactory}.
@@ -63,11 +82,11 @@ public class DefaultDbRefResolver extends DefaultReferenceResolver implements Db
*/
public DefaultDbRefResolver(MongoDatabaseFactory mongoDbFactory) {
super(new MongoDatabaseFactoryReferenceLoader(mongoDbFactory), mongoDbFactory.getExceptionTranslator());
Assert.notNull(mongoDbFactory, "MongoDbFactory translator must not be null!");
this.mongoDbFactory = mongoDbFactory;
this.exceptionTranslator = mongoDbFactory.getExceptionTranslator();
this.objenesis = new ObjenesisStd(true);
}
/*
@@ -95,8 +114,17 @@ public class DefaultDbRefResolver extends DefaultReferenceResolver implements Db
*/
@Override
public Document fetch(DBRef dbRef) {
return getReferenceLoader().fetchOne(DocumentReferenceQuery.forSingleDocument(Filters.eq("_id", dbRef.getId())),
ReferenceCollection.fromDBRef(dbRef));
MongoCollection<Document> mongoCollection = getCollection(dbRef);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Fetching DBRef '{}' from {}.{}.", dbRef.getId(),
StringUtils.hasText(dbRef.getDatabaseName()) ? dbRef.getDatabaseName()
: mongoCollection.getNamespace().getDatabaseName(),
dbRef.getCollectionName());
}
return mongoCollection.find(Filters.eq("_id", dbRef.getId())).first();
}
/*
@@ -137,7 +165,7 @@ public class DefaultDbRefResolver extends DefaultReferenceResolver implements Db
}
List<Document> result = mongoCollection //
.find(new Document(BasicMongoPersistentProperty.ID_FIELD_NAME, new Document("$in", ids))) //
.find(new Document("_id", new Document("$in", ids))) //
.into(new ArrayList<>());
return ids.stream() //
@@ -157,9 +185,44 @@ public class DefaultDbRefResolver extends DefaultReferenceResolver implements Db
private Object createLazyLoadingProxy(MongoPersistentProperty property, @Nullable DBRef dbref,
DbRefResolverCallback callback, DbRefProxyHandler handler) {
Object lazyLoadingProxy = getProxyFactory().createLazyLoadingProxy(property, callback, dbref);
Class<?> propertyType = property.getType();
LazyLoadingInterceptor interceptor = new LazyLoadingInterceptor(property, dbref, exceptionTranslator, callback);
return handler.populateId(property, dbref, lazyLoadingProxy);
if (!propertyType.isInterface()) {
Factory factory = (Factory) objenesis.newInstance(getEnhancedTypeFor(propertyType));
factory.setCallbacks(new Callback[] { interceptor });
return handler.populateId(property, dbref, factory);
}
ProxyFactory proxyFactory = new ProxyFactory();
for (Class<?> type : propertyType.getInterfaces()) {
proxyFactory.addInterface(type);
}
proxyFactory.addInterface(LazyLoadingProxy.class);
proxyFactory.addInterface(propertyType);
proxyFactory.addAdvice(interceptor);
return handler.populateId(property, dbref, proxyFactory.getProxy(LazyLoadingProxy.class.getClassLoader()));
}
/**
* Returns the CGLib enhanced type for the given source type.
*
* @param type
* @return
*/
private Class<?> getEnhancedTypeFor(Class<?> type) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(type);
enhancer.setCallbackType(org.springframework.cglib.proxy.MethodInterceptor.class);
enhancer.setInterfaces(new Class[] { LazyLoadingProxy.class });
return enhancer.createClass();
}
/**
@@ -182,10 +245,253 @@ public class DefaultDbRefResolver extends DefaultReferenceResolver implements Db
private static Stream<Document> documentWithId(Object identifier, Collection<Document> documents) {
return documents.stream() //
.filter(it -> it.get(BasicMongoPersistentProperty.ID_FIELD_NAME).equals(identifier)) //
.filter(it -> it.get("_id").equals(identifier)) //
.limit(1);
}
/**
* A {@link MethodInterceptor} that is used within a lazy loading proxy. The property resolving is delegated to a
* {@link DbRefResolverCallback}. The resolving process is triggered by a method invocation on the proxy and is
* guaranteed to be performed only once.
*
* @author Thomas Darimont
* @author Oliver Gierke
* @author Christoph Strobl
*/
static class LazyLoadingInterceptor
implements MethodInterceptor, org.springframework.cglib.proxy.MethodInterceptor, Serializable {
private static final Method INITIALIZE_METHOD, TO_DBREF_METHOD, FINALIZE_METHOD;
private final DbRefResolverCallback callback;
private final MongoPersistentProperty property;
private final PersistenceExceptionTranslator exceptionTranslator;
private volatile boolean resolved;
private final @Nullable DBRef dbref;
private @Nullable Object result;
static {
try {
INITIALIZE_METHOD = LazyLoadingProxy.class.getMethod("getTarget");
TO_DBREF_METHOD = LazyLoadingProxy.class.getMethod("toDBRef");
FINALIZE_METHOD = Object.class.getDeclaredMethod("finalize");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Creates a new {@link LazyLoadingInterceptor} for the given {@link MongoPersistentProperty},
* {@link PersistenceExceptionTranslator} and {@link DbRefResolverCallback}.
*
* @param property must not be {@literal null}.
* @param dbref can be {@literal null}.
* @param callback must not be {@literal null}.
*/
public LazyLoadingInterceptor(MongoPersistentProperty property, @Nullable DBRef dbref,
PersistenceExceptionTranslator exceptionTranslator, DbRefResolverCallback callback) {
Assert.notNull(property, "Property must not be null!");
Assert.notNull(exceptionTranslator, "Exception translator must not be null!");
Assert.notNull(callback, "Callback must not be null!");
this.dbref = dbref;
this.callback = callback;
this.exceptionTranslator = exceptionTranslator;
this.property = property;
}
/*
* (non-Javadoc)
* @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
*/
@Override
public Object invoke(@Nullable MethodInvocation invocation) throws Throwable {
return intercept(invocation.getThis(), invocation.getMethod(), invocation.getArguments(), null);
}
/*
* (non-Javadoc)
* @see org.springframework.cglib.proxy.MethodInterceptor#intercept(java.lang.Object, java.lang.reflect.Method, java.lang.Object[], org.springframework.cglib.proxy.MethodProxy)
*/
@Nullable
@Override
public Object intercept(Object obj, Method method, Object[] args, @Nullable MethodProxy proxy) throws Throwable {
if (INITIALIZE_METHOD.equals(method)) {
return ensureResolved();
}
if (TO_DBREF_METHOD.equals(method)) {
return this.dbref;
}
if (isObjectMethod(method) && Object.class.equals(method.getDeclaringClass())) {
if (ReflectionUtils.isToStringMethod(method)) {
return proxyToString(proxy);
}
if (ReflectionUtils.isEqualsMethod(method)) {
return proxyEquals(proxy, args[0]);
}
if (ReflectionUtils.isHashCodeMethod(method)) {
return proxyHashCode(proxy);
}
// DATAMONGO-1076 - finalize methods should not trigger proxy initialization
if (FINALIZE_METHOD.equals(method)) {
return null;
}
}
Object target = ensureResolved();
if (target == null) {
return null;
}
ReflectionUtils.makeAccessible(method);
return method.invoke(target, args);
}
/**
* Returns a to string representation for the given {@code proxy}.
*
* @param proxy
* @return
*/
private String proxyToString(@Nullable Object proxy) {
StringBuilder description = new StringBuilder();
if (dbref != null) {
description.append(dbref.getCollectionName());
description.append(":");
description.append(dbref.getId());
} else {
description.append(System.identityHashCode(proxy));
}
description.append("$").append(LazyLoadingProxy.class.getSimpleName());
return description.toString();
}
/**
* Returns the hashcode for the given {@code proxy}.
*
* @param proxy
* @return
*/
private int proxyHashCode(@Nullable Object proxy) {
return proxyToString(proxy).hashCode();
}
/**
* Performs an equality check for the given {@code proxy}.
*
* @param proxy
* @param that
* @return
*/
private boolean proxyEquals(@Nullable Object proxy, Object that) {
if (!(that instanceof LazyLoadingProxy)) {
return false;
}
if (that == proxy) {
return true;
}
return proxyToString(proxy).equals(that.toString());
}
/**
* Will trigger the resolution if the proxy is not resolved already or return a previously resolved result.
*
* @return
*/
@Nullable
private Object ensureResolved() {
if (!resolved) {
this.result = resolve();
this.resolved = true;
}
return this.result;
}
/**
* Callback method for serialization.
*
* @param out
* @throws IOException
*/
private void writeObject(ObjectOutputStream out) throws IOException {
ensureResolved();
out.writeObject(this.result);
}
/**
* Callback method for deserialization.
*
* @param in
* @throws IOException
*/
private void readObject(ObjectInputStream in) throws IOException {
try {
this.resolved = true;
this.result = in.readObject();
} catch (ClassNotFoundException e) {
throw new LazyLoadingException("Could not deserialize result", e);
}
}
/**
* Resolves the proxy into its backing object.
*
* @return
*/
@Nullable
private synchronized Object resolve() {
if (resolved) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Accessing already resolved lazy loading property {}.{}",
property.getOwner() != null ? property.getOwner().getName() : "unknown", property.getName());
}
return result;
}
try {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Resolving lazy loading property {}.{}",
property.getOwner() != null ? property.getOwner().getName() : "unknown", property.getName());
}
return callback.resolve(property);
} catch (RuntimeException ex) {
DataAccessException translatedException = this.exceptionTranslator.translateExceptionIfPossible(ex);
if (translatedException instanceof ClientSessionException) {
throw new LazyLoadingException("Unable to lazily resolve DBRef! Invalid session state.", ex);
}
throw new LazyLoadingException("Unable to lazily resolve DBRef!",
translatedException != null ? translatedException : ex);
}
}
}
/**
* Customization hook for obtaining the {@link MongoCollection} for a given {@link DBRef}.
*
@@ -198,10 +504,4 @@ public class DefaultDbRefResolver extends DefaultReferenceResolver implements Db
return MongoDatabaseUtils.getDatabase(dbref.getDatabaseName(), mongoDbFactory)
.getCollection(dbref.getCollectionName(), Document.class);
}
protected MongoCollection<Document> getCollection(ReferenceCollection context) {
return MongoDatabaseUtils.getDatabase(context.getDatabase(), mongoDbFactory).getCollection(context.getCollection(),
Document.class);
}
}

View File

@@ -1,113 +0,0 @@
/*
* Copyright 2021 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.convert;
import static org.springframework.data.mongodb.core.convert.ReferenceLookupDelegate.*;
import java.util.Collections;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.DocumentReference;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.util.Assert;
/**
* {@link ReferenceResolver} implementation that uses a given {@link ReferenceLookupDelegate} to load and convert entity
* associations expressed via a {@link MongoPersistentProperty persitent property}. Creates {@link LazyLoadingProxy
* proxies} for associations that should be lazily loaded.
*
* @author Christoph Strobl
* @author Mark Paluch
* @since 3.3
*/
public class DefaultReferenceResolver implements ReferenceResolver {
private final ReferenceLoader referenceLoader;
private final LazyLoadingProxyFactory proxyFactory;
private final LookupFunction collectionLookupFunction = (filter, ctx) -> getReferenceLoader().fetchMany(filter, ctx);
private final LookupFunction singleValueLookupFunction = (filter, ctx) -> {
Object target = getReferenceLoader().fetchOne(filter, ctx);
return target == null ? Collections.emptyList() : Collections.singleton(getReferenceLoader().fetchOne(filter, ctx));
};
/**
* Create a new instance of {@link DefaultReferenceResolver}.
*
* @param referenceLoader must not be {@literal null}.
* @param exceptionTranslator must not be {@literal null}.
*/
public DefaultReferenceResolver(ReferenceLoader referenceLoader, PersistenceExceptionTranslator exceptionTranslator) {
Assert.notNull(referenceLoader, "ReferenceLoader must not be null!");
Assert.notNull(exceptionTranslator, "ExceptionTranslator must not be null!");
this.referenceLoader = referenceLoader;
this.proxyFactory = new LazyLoadingProxyFactory(exceptionTranslator);
}
@Override
public Object resolveReference(MongoPersistentProperty property, Object source,
ReferenceLookupDelegate referenceLookupDelegate, MongoEntityReader entityReader) {
LookupFunction lookupFunction = (property.isCollectionLike() || property.isMap()) ? collectionLookupFunction
: singleValueLookupFunction;
if (isLazyReference(property)) {
return createLazyLoadingProxy(property, source, referenceLookupDelegate, lookupFunction, entityReader);
}
return referenceLookupDelegate.readReference(property, source, lookupFunction, entityReader);
}
/**
* Check if the association expressed by the given {@link MongoPersistentProperty property} should be resolved lazily.
*
* @param property
* @return return {@literal true} if the defined association is lazy.
* @see DBRef#lazy()
* @see DocumentReference#lazy()
*/
protected boolean isLazyReference(MongoPersistentProperty property) {
if (property.isDocumentReference()) {
return property.getDocumentReference().lazy();
}
return property.getDBRef() != null && property.getDBRef().lazy();
}
/**
* The {@link ReferenceLoader} executing the lookup.
*
* @return never {@literal null}.
*/
protected ReferenceLoader getReferenceLoader() {
return referenceLoader;
}
LazyLoadingProxyFactory getProxyFactory() {
return proxyFactory;
}
private Object createLazyLoadingProxy(MongoPersistentProperty property, Object source,
ReferenceLookupDelegate referenceLookupDelegate, LookupFunction lookupFunction, MongoEntityReader entityReader) {
return proxyFactory.createLazyLoadingProxy(property, it -> {
return referenceLookupDelegate.readReference(it, source, lookupFunction, entityReader);
}, source);
}
}

View File

@@ -17,7 +17,6 @@ package org.springframework.data.mongodb.core.convert;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import org.bson.Document;
import org.bson.conversions.Bson;
@@ -67,19 +66,6 @@ class DocumentAccessor {
return this.document;
}
/**
* Copies all of the mappings from the given {@link Document} to the underlying target {@link Document}. These
* mappings will replace any mappings that the target document had for any of the keys currently in the specified map.
*
* @param source
*/
public void putAll(Document source) {
Map<String, Object> target = BsonUtils.asMap(document);
target.putAll(source);
}
/**
* Puts the given value into the backing {@link Document} based on the coordinates defined through the given
* {@link MongoPersistentProperty}. By default this will be the plain field name. But field names might also consist
@@ -133,7 +119,6 @@ class DocumentAccessor {
* @param entity must not be {@literal null}.
* @return
*/
@Nullable
public Object getRawId(MongoPersistentEntity<?> entity) {
return entity.hasIdProperty() ? get(entity.getRequiredIdProperty()) : BsonUtils.asMap(document).get("_id");
}

View File

@@ -1,237 +0,0 @@
/*
* Copyright 2021 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.convert;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.WeakHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bson.Document;
import org.springframework.core.convert.ConversionService;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.annotation.Reference;
import org.springframework.data.mapping.PersistentPropertyAccessor;
import org.springframework.data.mapping.PersistentPropertyPath;
import org.springframework.data.mapping.PropertyPath;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mapping.model.BeanWrapperPropertyAccessorFactory;
import org.springframework.data.mongodb.core.mapping.DocumentPointer;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
/**
* Internal API to construct {@link DocumentPointer} for a given property. Considers {@link LazyLoadingProxy},
* registered {@link Object} to {@link DocumentPointer} {@link org.springframework.core.convert.converter.Converter},
* simple {@literal _id} lookups and cases where the {@link DocumentPointer} needs to be computed via a lookup query.
*
* @author Christoph Strobl
* @since 3.3
*/
class DocumentPointerFactory {
private final ConversionService conversionService;
private final MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext;
private final Map<String, LinkageDocument> cache;
/**
* A {@link Pattern} matching quoted and unquoted variants (with/out whitespaces) of
* <code>{'_id' : ?#{#target} }</code>.
*/
private static final Pattern DEFAULT_LOOKUP_PATTERN = Pattern.compile("\\{\\s?" + // document start (whitespace opt)
"['\"]?_id['\"]?" + // followed by an optionally quoted _id. Like: _id, '_id' or "_id"
"?\\s?:\\s?" + // then a colon optionally wrapped inside whitespaces
"['\"]?\\?#\\{#target\\}['\"]?" + // leading to the potentially quoted ?#{#target} expression
"\\s*}"); // some optional whitespaces and document close
DocumentPointerFactory(ConversionService conversionService,
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext) {
this.conversionService = conversionService;
this.mappingContext = mappingContext;
this.cache = new WeakHashMap<>();
}
DocumentPointer<?> computePointer(
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext,
MongoPersistentProperty property, Object value, Class<?> typeHint) {
if (value instanceof LazyLoadingProxy) {
return () -> ((LazyLoadingProxy) value).getSource();
}
if (conversionService.canConvert(typeHint, DocumentPointer.class)) {
return conversionService.convert(value, DocumentPointer.class);
}
MongoPersistentEntity<?> persistentEntity = mappingContext
.getRequiredPersistentEntity(property.getAssociationTargetType());
if (usesDefaultLookup(property)) {
return () -> persistentEntity.getIdentifierAccessor(value).getIdentifier();
}
MongoPersistentEntity<?> valueEntity = mappingContext.getPersistentEntity(value.getClass());
PersistentPropertyAccessor<Object> propertyAccessor;
if (valueEntity == null) {
propertyAccessor = BeanWrapperPropertyAccessorFactory.INSTANCE.getPropertyAccessor(property.getOwner(), value);
} else {
propertyAccessor = valueEntity.getPropertyPathAccessor(value);
}
return cache.computeIfAbsent(property.getDocumentReference().lookup(), LinkageDocument::from)
.getDocumentPointer(mappingContext, persistentEntity, propertyAccessor);
}
private boolean usesDefaultLookup(MongoPersistentProperty property) {
if (property.isDocumentReference()) {
return DEFAULT_LOOKUP_PATTERN.matcher(property.getDocumentReference().lookup()).matches();
}
Reference atReference = property.findAnnotation(Reference.class);
if (atReference != null) {
return true;
}
throw new IllegalStateException(String.format("%s does not seem to be define Reference", property));
}
/**
* Value object that computes a document pointer from a given lookup query by identifying SpEL expressions and
* inverting it.
*
* <pre class="code">
* // source
* { 'firstname' : ?#{fn}, 'lastname' : '?#{ln} }
*
* // target
* { 'fn' : ..., 'ln' : ... }
* </pre>
*
* The actual pointer is the computed via
* {@link #getDocumentPointer(MappingContext, MongoPersistentEntity, PersistentPropertyAccessor)} applying values from
* the provided {@link PersistentPropertyAccessor} to the target document by looking at the keys of the expressions
* from the source.
*/
static class LinkageDocument {
static final Pattern EXPRESSION_PATTERN = Pattern.compile("\\?#\\{#?(?<fieldName>[\\w\\d\\.\\-)]*)\\}");
static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("###_(?<index>\\d*)_###");
private final String lookup;
private final org.bson.Document documentPointer;
private final Map<String, String> placeholderMap;
static LinkageDocument from(String lookup) {
return new LinkageDocument(lookup);
}
private LinkageDocument(String lookup) {
this.lookup = lookup;
this.placeholderMap = new LinkedHashMap<>();
int index = 0;
Matcher matcher = EXPRESSION_PATTERN.matcher(lookup);
String targetLookup = lookup;
while (matcher.find()) {
String expression = matcher.group();
String fieldName = matcher.group("fieldName").replace("target.", "");
String placeholder = placeholder(index);
placeholderMap.put(placeholder, fieldName);
targetLookup = targetLookup.replace(expression, "'" + placeholder + "'");
index++;
}
this.documentPointer = org.bson.Document.parse(targetLookup);
}
private String placeholder(int index) {
return "###_" + index + "_###";
}
private boolean isPlaceholder(String key) {
return PLACEHOLDER_PATTERN.matcher(key).matches();
}
DocumentPointer<Object> getDocumentPointer(
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext,
MongoPersistentEntity<?> persistentEntity, PersistentPropertyAccessor<?> propertyAccessor) {
return () -> updatePlaceholders(documentPointer, new Document(), mappingContext, persistentEntity,
propertyAccessor);
}
Document updatePlaceholders(org.bson.Document source, org.bson.Document target,
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext,
MongoPersistentEntity<?> persistentEntity, PersistentPropertyAccessor<?> propertyAccessor) {
for (Entry<String, Object> entry : source.entrySet()) {
if (entry.getKey().startsWith("$")) {
throw new InvalidDataAccessApiUsageException(String.format(
"Cannot derive document pointer from lookup '%s' using query operator (%s). Please consider registering a custom converter.",
lookup, entry.getKey()));
}
if (entry.getValue() instanceof Document) {
MongoPersistentProperty persistentProperty = persistentEntity.getPersistentProperty(entry.getKey());
if (persistentProperty != null && persistentProperty.isEntity()) {
MongoPersistentEntity<?> nestedEntity = mappingContext.getPersistentEntity(persistentProperty.getType());
target.put(entry.getKey(), updatePlaceholders((Document) entry.getValue(), new Document(), mappingContext,
nestedEntity, nestedEntity.getPropertyAccessor(propertyAccessor.getProperty(persistentProperty))));
} else {
target.put(entry.getKey(), updatePlaceholders((Document) entry.getValue(), new Document(), mappingContext,
persistentEntity, propertyAccessor));
}
continue;
}
if (placeholderMap.containsKey(entry.getValue())) {
String attribute = placeholderMap.get(entry.getValue());
if (attribute.contains(".")) {
attribute = attribute.substring(attribute.lastIndexOf('.') + 1);
}
String fieldName = entry.getKey().equals("_id") ? "id" : entry.getKey();
if (!fieldName.contains(".")) {
Object targetValue = propertyAccessor.getProperty(persistentEntity.getPersistentProperty(fieldName));
target.put(attribute, targetValue);
continue;
}
PersistentPropertyPath<?> path = mappingContext
.getPersistentPropertyPath(PropertyPath.from(fieldName, persistentEntity.getTypeInformation()));
Object targetValue = propertyAccessor.getProperty(path);
target.put(attribute, targetValue);
continue;
}
target.put(entry.getKey(), entry.getValue());
}
return target;
}
}
}

View File

@@ -15,18 +15,18 @@
*/
package org.springframework.data.mongodb.core.convert;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver.LazyLoadingInterceptor;
import org.springframework.lang.Nullable;
import com.mongodb.DBRef;
/**
* Allows direct interaction with the underlying {@code LazyLoadingInterceptor}.
* Allows direct interaction with the underlying {@link LazyLoadingInterceptor}.
*
* @author Thomas Darimont
* @author Christoph Strobl
* @author Mark Paluch
* @since 1.5
* @see LazyLoadingProxyFactory
*/
public interface LazyLoadingProxy {
@@ -46,15 +46,4 @@ public interface LazyLoadingProxy {
*/
@Nullable
DBRef toDBRef();
/**
* Returns the raw {@literal source} object that defines the reference.
*
* @return can be {@literal null}.
* @since 3.3
*/
@Nullable
default Object getSource() {
return toDBRef();
}
}

View File

@@ -1,303 +0,0 @@
/*
* Copyright 2021 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.convert;
import static org.springframework.util.ReflectionUtils.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.Factory;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.data.mongodb.ClientSessionException;
import org.springframework.data.mongodb.LazyLoadingException;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.lang.Nullable;
import org.springframework.objenesis.ObjenesisStd;
import org.springframework.util.ReflectionUtils;
import com.mongodb.DBRef;
/**
* {@link ProxyFactory} to create a proxy for {@link MongoPersistentProperty#getType()} to resolve a reference lazily.
*
* @author Christoph Strobl
* @author Mark Paluch
*/
class LazyLoadingProxyFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(LazyLoadingProxyFactory.class);
private final ObjenesisStd objenesis;
private final PersistenceExceptionTranslator exceptionTranslator;
public LazyLoadingProxyFactory(PersistenceExceptionTranslator exceptionTranslator) {
this.exceptionTranslator = exceptionTranslator;
this.objenesis = new ObjenesisStd(true);
}
public Object createLazyLoadingProxy(MongoPersistentProperty property, DbRefResolverCallback callback,
Object source) {
Class<?> propertyType = property.getType();
LazyLoadingInterceptor interceptor = new LazyLoadingInterceptor(property, callback, source, exceptionTranslator);
if (!propertyType.isInterface()) {
Factory factory = (Factory) objenesis.newInstance(getEnhancedTypeFor(propertyType));
factory.setCallbacks(new Callback[] { interceptor });
return factory;
}
ProxyFactory proxyFactory = new ProxyFactory();
for (Class<?> type : propertyType.getInterfaces()) {
proxyFactory.addInterface(type);
}
proxyFactory.addInterface(LazyLoadingProxy.class);
proxyFactory.addInterface(propertyType);
proxyFactory.addAdvice(interceptor);
return proxyFactory.getProxy(LazyLoadingProxy.class.getClassLoader());
}
/**
* Returns the CGLib enhanced type for the given source type.
*
* @param type
* @return
*/
private Class<?> getEnhancedTypeFor(Class<?> type) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(type);
enhancer.setCallbackType(org.springframework.cglib.proxy.MethodInterceptor.class);
enhancer.setInterfaces(new Class[] { LazyLoadingProxy.class });
return enhancer.createClass();
}
public static class LazyLoadingInterceptor
implements MethodInterceptor, org.springframework.cglib.proxy.MethodInterceptor, Serializable {
private static final Method INITIALIZE_METHOD, TO_DBREF_METHOD, FINALIZE_METHOD, GET_SOURCE_METHOD;
static {
try {
INITIALIZE_METHOD = LazyLoadingProxy.class.getMethod("getTarget");
TO_DBREF_METHOD = LazyLoadingProxy.class.getMethod("toDBRef");
FINALIZE_METHOD = Object.class.getDeclaredMethod("finalize");
GET_SOURCE_METHOD = LazyLoadingProxy.class.getMethod("getSource");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private final MongoPersistentProperty property;
private final DbRefResolverCallback callback;
private final Object source;
private final PersistenceExceptionTranslator exceptionTranslator;
private volatile boolean resolved;
private @Nullable Object result;
public LazyLoadingInterceptor(MongoPersistentProperty property, DbRefResolverCallback callback, Object source,
PersistenceExceptionTranslator exceptionTranslator) {
this.property = property;
this.callback = callback;
this.source = source;
this.exceptionTranslator = exceptionTranslator;
}
@Nullable
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
return intercept(invocation.getThis(), invocation.getMethod(), invocation.getArguments(), null);
}
@Nullable
@Override
public Object intercept(Object o, Method method, Object[] args, MethodProxy proxy) throws Throwable {
if (INITIALIZE_METHOD.equals(method)) {
return ensureResolved();
}
if (TO_DBREF_METHOD.equals(method)) {
return source instanceof DBRef ? source : null;
}
if (GET_SOURCE_METHOD.equals(method)) {
return source;
}
if (isObjectMethod(method) && Object.class.equals(method.getDeclaringClass())) {
if (ReflectionUtils.isToStringMethod(method)) {
return proxyToString(source);
}
if (ReflectionUtils.isEqualsMethod(method)) {
return proxyEquals(o, args[0]);
}
if (ReflectionUtils.isHashCodeMethod(method)) {
return proxyHashCode();
}
// DATAMONGO-1076 - finalize methods should not trigger proxy initialization
if (FINALIZE_METHOD.equals(method)) {
return null;
}
}
Object target = ensureResolved();
if (target == null) {
return null;
}
ReflectionUtils.makeAccessible(method);
return method.invoke(target, args);
}
@Nullable
private Object ensureResolved() {
if (!resolved) {
this.result = resolve();
this.resolved = true;
}
return this.result;
}
private String proxyToString(@Nullable Object source) {
StringBuilder description = new StringBuilder();
if (source != null) {
if (source instanceof DBRef) {
description.append(((DBRef) source).getCollectionName());
description.append(":");
description.append(((DBRef) source).getId());
} else {
description.append(source);
}
} else {
description.append(System.identityHashCode(source));
}
description.append("$").append(LazyLoadingProxy.class.getSimpleName());
return description.toString();
}
private boolean proxyEquals(@Nullable Object proxy, Object that) {
if (!(that instanceof LazyLoadingProxy)) {
return false;
}
if (that == proxy) {
return true;
}
return proxyToString(proxy).equals(that.toString());
}
private int proxyHashCode() {
return proxyToString(source).hashCode();
}
/**
* Callback method for serialization.
*
* @param out
* @throws IOException
*/
private void writeObject(ObjectOutputStream out) throws IOException {
ensureResolved();
out.writeObject(this.result);
}
/**
* Callback method for deserialization.
*
* @param in
* @throws IOException
*/
private void readObject(ObjectInputStream in) throws IOException {
try {
this.resolved = true;
this.result = in.readObject();
} catch (ClassNotFoundException e) {
throw new LazyLoadingException("Could not deserialize result", e);
}
}
@Nullable
private synchronized Object resolve() {
if (resolved) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Accessing already resolved lazy loading property {}.{}",
property.getOwner() != null ? property.getOwner().getName() : "unknown", property.getName());
}
return result;
}
try {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Resolving lazy loading property {}.{}",
property.getOwner() != null ? property.getOwner().getName() : "unknown", property.getName());
}
return callback.resolve(property);
} catch (RuntimeException ex) {
DataAccessException translatedException = exceptionTranslator.translateExceptionIfPossible(ex);
if (translatedException instanceof ClientSessionException) {
throw new LazyLoadingException("Unable to lazily resolve DBRef! Invalid session state.", ex);
}
throw new LazyLoadingException("Unable to lazily resolve DBRef!",
translatedException != null ? translatedException : ex);
}
}
}
}

View File

@@ -26,7 +26,6 @@ import org.springframework.data.convert.TypeMapper;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.util.BsonUtils;
import org.springframework.data.util.TypeInformation;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
@@ -145,9 +144,9 @@ public interface MongoConverter
try {
return getConversionService().canConvert(id.getClass(), targetType)
? getConversionService().convert(id, targetType)
: convertToMongoType(id, (TypeInformation<?>) null);
: convertToMongoType(id, null);
} catch (ConversionException o_O) {
return convertToMongoType(id,(TypeInformation<?>) null);
return convertToMongoType(id, null);
}
}
}

View File

@@ -27,18 +27,14 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Currency;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.bson.BsonReader;
import org.bson.BsonTimestamp;
import org.bson.BsonWriter;
import org.bson.Document;
import org.bson.UuidRepresentation;
import org.bson.codecs.Codec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.internal.CodecRegistryHelper;
import org.bson.types.Binary;
import org.bson.types.Code;
import org.bson.types.Decimal128;
@@ -244,23 +240,9 @@ abstract class MongoConverters {
INSTANCE;
private final Codec<Document> codec = CodecRegistries.fromRegistries(CodecRegistries.fromCodecs(new Codec<UUID>() {
@Override
public void encode(BsonWriter writer, UUID value, EncoderContext encoderContext) {
writer.writeString(value.toString());
}
@Override
public Class<UUID> getEncoderClass() {
return UUID.class;
}
@Override
public UUID decode(BsonReader reader, DecoderContext decoderContext) {
throw new IllegalStateException("decode not supported");
}
}), MongoClientSettings.getDefaultCodecRegistry()).get(Document.class);
private final Codec<Document> codec = CodecRegistryHelper
.createRegistry(MongoClientSettings.getDefaultCodecRegistry(), UuidRepresentation.JAVA_LEGACY)
.get(Document.class);
@Override
public String convert(Document source) {
@@ -294,7 +276,7 @@ abstract class MongoConverters {
@Override
public NamedMongoScript convert(Document source) {
if (source.isEmpty()) {
if(source.isEmpty()) {
return null;
}

View File

@@ -1,79 +0,0 @@
/*
* Copyright 2021 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.convert;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.MongoDatabaseUtils;
import org.springframework.data.mongodb.core.convert.ReferenceResolver.ReferenceCollection;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import com.mongodb.client.MongoCollection;
/**
* {@link ReferenceLoader} implementation using a {@link MongoDatabaseFactory} to obtain raw {@link Document documents}
* for linked entities via a {@link ReferenceLoader.DocumentReferenceQuery}.
*
* @author Christoph Strobl
* @since 3.3
*/
public class MongoDatabaseFactoryReferenceLoader implements ReferenceLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(MongoDatabaseFactoryReferenceLoader.class);
private final MongoDatabaseFactory mongoDbFactory;
/**
* @param mongoDbFactory must not be {@literal null}.
*/
public MongoDatabaseFactoryReferenceLoader(MongoDatabaseFactory mongoDbFactory) {
Assert.notNull(mongoDbFactory, "MongoDbFactory translator must not be null!");
this.mongoDbFactory = mongoDbFactory;
}
@Override
public Iterable<Document> fetchMany(DocumentReferenceQuery referenceQuery, ReferenceCollection context) {
MongoCollection<Document> collection = getCollection(context);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Bulk fetching {} from {}.{}.", referenceQuery,
StringUtils.hasText(context.getDatabase()) ? context.getDatabase()
: collection.getNamespace().getDatabaseName(),
context.getCollection());
}
return referenceQuery.apply(collection);
}
/**
* Obtain the {@link MongoCollection} for a given {@link ReferenceCollection} from the underlying
* {@link MongoDatabaseFactory}.
*
* @param context must not be {@literal null}.
* @return the {@link MongoCollection} targeted by the {@link ReferenceCollection}.
*/
protected MongoCollection<Document> getCollection(ReferenceCollection context) {
return MongoDatabaseUtils.getDatabase(context.getDatabase(), mongoDbFactory).getCollection(context.getCollection(),
Document.class);
}
}

View File

@@ -40,7 +40,6 @@ import org.springframework.data.mongodb.core.query.MongoRegexCreator;
import org.springframework.data.mongodb.core.query.MongoRegexCreator.MatchMode;
import org.springframework.data.mongodb.core.query.SerializationUtils;
import org.springframework.data.mongodb.core.query.UntypedExampleMatcher;
import org.springframework.data.mongodb.util.DotPath;
import org.springframework.data.support.ExampleMatcherAccessor;
import org.springframework.data.util.TypeInformation;
import org.springframework.util.Assert;
@@ -135,7 +134,7 @@ public class MongoExampleMapper {
while (iter.hasNext()) {
Map.Entry<String, Object> entry = iter.next();
String propertyPath = DotPath.from(path).append(entry.getKey()).toString();
String propertyPath = StringUtils.hasText(path) ? path + "." + entry.getKey() : entry.getKey();
String mappedPropertyPath = getMappedPropertyPath(propertyPath, probeType);
if (isEmptyIdProperty(entry)) {

View File

@@ -17,9 +17,6 @@ package org.springframework.data.mongodb.core.convert;
import org.bson.conversions.Bson;
import org.springframework.data.convert.EntityWriter;
import org.springframework.data.mongodb.core.mapping.DocumentPointer;
import org.springframework.data.mongodb.core.mapping.DocumentReference;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.util.TypeInformation;
import org.springframework.lang.Nullable;
@@ -46,7 +43,7 @@ public interface MongoWriter<T> extends EntityWriter<T, Bson> {
*/
@Nullable
default Object convertToMongoType(@Nullable Object obj) {
return convertToMongoType(obj, (TypeInformation<?>) null);
return convertToMongoType(obj, null);
}
/**
@@ -60,10 +57,6 @@ public interface MongoWriter<T> extends EntityWriter<T, Bson> {
@Nullable
Object convertToMongoType(@Nullable Object obj, @Nullable TypeInformation<?> typeInformation);
default Object convertToMongoType(@Nullable Object obj, MongoPersistentEntity<?> entity) {
return convertToMongoType(obj, entity.getTypeInformation());
}
/**
* Creates a {@link DBRef} to refer to the given object.
*
@@ -73,17 +66,4 @@ public interface MongoWriter<T> extends EntityWriter<T, Bson> {
* @return will never be {@literal null}.
*/
DBRef toDBRef(Object object, @Nullable MongoPersistentProperty referingProperty);
/**
* Creates a the {@link DocumentPointer} representing the link to another entity.
*
* @param source the object to create a document link to.
* @param referringProperty the client-side property referring to the object which might carry additional metadata for
* the {@link DBRef} object to create. Can be {@literal null}.
* @return will never be {@literal null}.
* @since 3.3
*/
default DocumentPointer<?> toDocumentPointer(Object source, @Nullable MongoPersistentProperty referringProperty) {
return () -> toDBRef(source, referringProperty);
}
}

View File

@@ -18,7 +18,6 @@ package org.springframework.data.mongodb.core.convert;
import java.util.List;
import org.bson.Document;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.lang.Nullable;
@@ -70,11 +69,4 @@ public enum NoOpDbRefResolver implements DbRefResolver {
private <T> T handle() throws UnsupportedOperationException {
throw new UnsupportedOperationException("DBRef resolution is not supported!");
}
@Nullable
@Override
public Object resolveReference(MongoPersistentProperty property, Object source,
ReferenceLookupDelegate referenceLookupDelegate, MongoEntityReader entityReader) {
return null;
}
}

View File

@@ -29,7 +29,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.annotation.Reference;
import org.springframework.data.domain.Example;
import org.springframework.data.mapping.Association;
import org.springframework.data.mapping.MappingException;
@@ -40,14 +39,12 @@ import org.springframework.data.mapping.PropertyPath;
import org.springframework.data.mapping.PropertyReferenceException;
import org.springframework.data.mapping.context.InvalidPersistentPropertyPath;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.MongoExpression;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter.NestedDocument;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty.PropertyToFieldNameConverter;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.util.BsonUtils;
import org.springframework.data.mongodb.util.DotPath;
import org.springframework.data.util.ClassTypeInformation;
import org.springframework.data.util.TypeInformation;
import org.springframework.lang.Nullable;
@@ -149,23 +146,9 @@ public class QueryMapper {
try {
Field field = createPropertyField(entity, key, mappingContext);
Entry<String, Object> entry = getMappedObjectForField(field, BsonUtils.get(query, key));
// TODO: move to dedicated method
if (field.getProperty() != null && field.getProperty().isUnwrapped()) {
Object theNestedObject = BsonUtils.get(query, key);
Document mappedValue = (Document) getMappedValue(field, theNestedObject);
if (!StringUtils.hasText(field.getMappedKey())) {
result.putAll(mappedValue);
} else {
result.put(field.getMappedKey(), mappedValue);
}
} else {
Entry<String, Object> entry = getMappedObjectForField(field, BsonUtils.get(query, key));
result.put(entry.getKey(), entry.getValue());
}
result.put(entry.getKey(), entry.getValue());
} catch (InvalidPersistentPropertyPath invalidPathException) {
// in case the object has not already been mapped
@@ -196,7 +179,13 @@ public class QueryMapper {
return new Document();
}
Document mappedSort = mapFieldsToPropertyNames(sortObject, entity);
Document mappedSort = new Document();
for (Map.Entry<String, Object> entry : BsonUtils.asMap(sortObject).entrySet()) {
Field field = createPropertyField(entity, entry.getKey(), mappingContext);
mappedSort.put(field.getMappedKey(), entry.getValue());
}
mapMetaAttributes(mappedSort, entity, MetaMapping.WHEN_PRESENT);
return mappedSort;
}
@@ -214,30 +203,11 @@ public class QueryMapper {
Assert.notNull(fieldsObject, "FieldsObject must not be null!");
Document mappedFields = mapFieldsToPropertyNames(fieldsObject, entity);
Document mappedFields = fieldsObject.isEmpty() ? new Document() : getMappedObject(fieldsObject, entity);
mapMetaAttributes(mappedFields, entity, MetaMapping.FORCE);
return mappedFields;
}
private Document mapFieldsToPropertyNames(Document fields, @Nullable MongoPersistentEntity<?> entity) {
if (fields.isEmpty()) {
return new Document();
}
Document target = new Document();
for (Map.Entry<String, Object> entry : BsonUtils.asMap(filterUnwrappedObjects(fields, entity)).entrySet()) {
Field field = createPropertyField(entity, entry.getKey(), mappingContext);
if (field.getProperty() != null && field.getProperty().isUnwrapped()) {
continue;
}
target.put(field.getMappedKey(), entry.getValue());
}
return target;
}
private void mapMetaAttributes(Document source, @Nullable MongoPersistentEntity<?> entity, MetaMapping metaMapping) {
if (entity == null) {
@@ -253,44 +223,6 @@ public class QueryMapper {
}
}
private Document filterUnwrappedObjects(Document fieldsObject, @Nullable MongoPersistentEntity<?> entity) {
if (fieldsObject.isEmpty() || entity == null) {
return fieldsObject;
}
Document target = new Document();
for (Entry<String, Object> field : fieldsObject.entrySet()) {
try {
PropertyPath path = PropertyPath.from(field.getKey(), entity.getTypeInformation());
PersistentPropertyPath<MongoPersistentProperty> persistentPropertyPath = mappingContext
.getPersistentPropertyPath(path);
MongoPersistentProperty property = mappingContext.getPersistentPropertyPath(path).getRequiredLeafProperty();
if (property.isUnwrapped() && property.isEntity()) {
MongoPersistentEntity<?> unwrappedEntity = mappingContext.getRequiredPersistentEntity(property);
for (MongoPersistentProperty unwrappedProperty : unwrappedEntity) {
DotPath dotPath = DotPath.from(persistentPropertyPath.toDotPath()).append(unwrappedProperty.getName());
target.put(dotPath.toString(), field.getValue());
}
} else {
target.put(field.getKey(), field.getValue());
}
} catch (RuntimeException e) {
target.put(field.getKey(), field.getValue());
}
}
return target;
}
private Document getMappedTextScoreField(MongoPersistentProperty property) {
return new Document(property.getFieldName(), META_TEXT_SCORE);
}
@@ -307,10 +239,6 @@ public class QueryMapper {
String key = field.getMappedKey();
Object value;
if (rawValue instanceof MongoExpression) {
return createMapEntry(key, getMappedObject(((MongoExpression) rawValue).toDocument(), field.getEntity()));
}
if (isNestedKeyword(rawValue) && !field.isIdField()) {
Keyword keyword = new Keyword((Document) rawValue);
value = getMappedKeyword(field, keyword);
@@ -579,11 +507,6 @@ public class QueryMapper {
*/
@Nullable
protected Object delegateConvertToMongoType(Object source, @Nullable MongoPersistentEntity<?> entity) {
if (entity != null && entity.isUnwrapped()) {
return converter.convertToMongoType(source, entity);
}
return converter.convertToMongoType(source, entity == null ? null : entity.getTypeInformation());
}
@@ -621,7 +544,7 @@ public class QueryMapper {
if (source instanceof Iterable) {
BasicDBList result = new BasicDBList();
for (Object element : (Iterable<?>) source) {
result.add(createReferenceFor(element, property));
result.add(createDbRefFor(element, property));
}
return result;
}
@@ -630,12 +553,12 @@ public class QueryMapper {
Document result = new Document();
Document dbObject = (Document) source;
for (String key : dbObject.keySet()) {
result.put(key, createReferenceFor(dbObject.get(key), property));
result.put(key, createDbRefFor(dbObject.get(key), property));
}
return result;
}
return createReferenceFor(source, property);
return createDbRefFor(source, property);
}
/**
@@ -682,17 +605,12 @@ public class QueryMapper {
return Collections.singletonMap(key, value).entrySet().iterator().next();
}
private Object createReferenceFor(Object source, MongoPersistentProperty property) {
private DBRef createDbRefFor(Object source, MongoPersistentProperty property) {
if (source instanceof DBRef) {
return (DBRef) source;
}
if (property != null && (property.isDocumentReference()
|| (!property.isDbReference() && property.findAnnotation(Reference.class) != null))) {
return converter.toDocumentPointer(source, property).getPointer();
}
return converter.toDBRef(source, property);
}
@@ -959,11 +877,6 @@ public class QueryMapper {
return null;
}
@Nullable
MongoPersistentEntity<?> getEntity() {
return null;
}
/**
* Returns whether the field represents an association.
*
@@ -1009,7 +922,6 @@ public class QueryMapper {
public TypeInformation<?> getTypeHint() {
return ClassTypeInformation.OBJECT;
}
}
/**
@@ -1116,12 +1028,6 @@ public class QueryMapper {
return property == null ? null : mappingContext.getPersistentEntity(property);
}
@Nullable
@Override
public MongoPersistentEntity<?> getEntity() {
return entity;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#isAssociation()

View File

@@ -1,130 +0,0 @@
/*
* Copyright 2021 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.convert;
import java.util.Collections;
import java.util.Iterator;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.data.mongodb.core.convert.ReferenceResolver.ReferenceCollection;
import org.springframework.lang.Nullable;
import com.mongodb.client.MongoCollection;
/**
* The {@link ReferenceLoader} obtains raw {@link Document documents} for linked entities via a
* {@link ReferenceLoader.DocumentReferenceQuery}.
*
* @author Christoph Strobl
* @since 3.3
*/
public interface ReferenceLoader {
/**
* Obtain a single {@link Document} matching the given {@literal referenceQuery} in the {@literal context}.
*
* @param referenceQuery must not be {@literal null}.
* @param context must not be {@literal null}.
* @return the matching {@link Document} or {@literal null} if none found.
*/
@Nullable
default Document fetchOne(DocumentReferenceQuery referenceQuery, ReferenceCollection context) {
Iterator<Document> it = fetchMany(referenceQuery, context).iterator();
return it.hasNext() ? it.next() : null;
}
/**
* Obtain multiple {@link Document} matching the given {@literal referenceQuery} in the {@literal context}.
*
* @param referenceQuery must not be {@literal null}.
* @param context must not be {@literal null}.
* @return the matching {@link Document} or {@literal null} if none found.
*/
Iterable<Document> fetchMany(DocumentReferenceQuery referenceQuery, ReferenceCollection context);
/**
* The {@link DocumentReferenceQuery} defines the criteria by which {@link Document documents} should be matched
* applying potentially given order criteria.
*/
interface DocumentReferenceQuery {
/**
* Get the query to obtain matching {@link Document documents}.
*
* @return never {@literal null}.
*/
Bson getQuery();
/**
* Get the sort criteria for ordering results.
*
* @return an empty {@link Document} by default. Never {@literal null}.
*/
default Bson getSort() {
return new Document();
}
default Iterable<Document> apply(MongoCollection<Document> collection) {
return restoreOrder(collection.find(getQuery()).sort(getSort()));
}
/**
* Restore the order of fetched documents.
*
* @param documents must not be {@literal null}.
* @return never {@literal null}.
*/
default Iterable<Document> restoreOrder(Iterable<Document> documents) {
return documents;
}
static DocumentReferenceQuery forSingleDocument(Bson bson) {
return new DocumentReferenceQuery() {
@Override
public Bson getQuery() {
return bson;
}
@Override
public Iterable<Document> apply(MongoCollection<Document> collection) {
Document result = collection.find(getQuery()).sort(getSort()).limit(1).first();
return result != null ? Collections.singleton(result) : Collections.emptyList();
}
};
}
static DocumentReferenceQuery forManyDocuments(Bson bson) {
return new DocumentReferenceQuery() {
@Override
public Bson getQuery() {
return bson;
}
@Override
public Iterable<Document> apply(MongoCollection<Document> collection) {
return collection.find(getQuery()).sort(getSort());
}
};
}
}
}

View File

@@ -1,451 +0,0 @@
/*
* Copyright 2021 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.convert;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mapping.model.SpELContext;
import org.springframework.data.mongodb.core.convert.ReferenceLoader.DocumentReferenceQuery;
import org.springframework.data.mongodb.core.convert.ReferenceResolver.MongoEntityReader;
import org.springframework.data.mongodb.core.convert.ReferenceResolver.ReferenceCollection;
import org.springframework.data.mongodb.core.mapping.DocumentReference;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.util.BsonUtils;
import org.springframework.data.mongodb.util.json.ParameterBindingContext;
import org.springframework.data.mongodb.util.json.ParameterBindingDocumentCodec;
import org.springframework.data.mongodb.util.json.ValueProvider;
import org.springframework.data.util.Streamable;
import org.springframework.expression.EvaluationContext;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import com.mongodb.DBRef;
import com.mongodb.client.MongoCollection;
/**
* A common delegate for {@link ReferenceResolver} implementations to resolve a reference to one/many target documents
* that are converted to entities.
*
* @author Christoph Strobl
* @author Mark Paluch
* @since 3.3
*/
public final class ReferenceLookupDelegate {
private final MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext;
private final SpELContext spELContext;
private final ParameterBindingDocumentCodec codec;
/**
* Create a new {@link ReferenceLookupDelegate}.
*
* @param mappingContext must not be {@literal null}.
* @param spELContext must not be {@literal null}.
*/
public ReferenceLookupDelegate(
MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext,
SpELContext spELContext) {
Assert.notNull(mappingContext, "MappingContext must not be null");
Assert.notNull(spELContext, "SpELContext must not be null");
this.mappingContext = mappingContext;
this.spELContext = spELContext;
this.codec = new ParameterBindingDocumentCodec();
}
/**
* Read the reference expressed by the given property.
*
* @param property the reference defining property. Must not be {@literal null}. THe
* @param value the source value identifying to the referenced entity. Must not be {@literal null}.
* @param lookupFunction to execute a lookup query. Must not be {@literal null}.
* @param entityReader the callback to convert raw source values into actual domain types. Must not be
* {@literal null}.
* @return can be {@literal null}.
*/
@Nullable
public Object readReference(MongoPersistentProperty property, Object value, LookupFunction lookupFunction,
MongoEntityReader entityReader) {
DocumentReferenceQuery filter = computeFilter(property, value, spELContext);
ReferenceCollection referenceCollection = computeReferenceContext(property, value, spELContext);
Iterable<Document> result = lookupFunction.apply(filter, referenceCollection);
if (property.isCollectionLike()) {
return entityReader.read(result, property.getTypeInformation());
}
if (!result.iterator().hasNext()) {
return null;
}
Object resultValue = result.iterator().next();
return resultValue != null ? entityReader.read(resultValue, property.getTypeInformation()) : null;
}
private ReferenceCollection computeReferenceContext(MongoPersistentProperty property, Object value,
SpELContext spELContext) {
// Use the first value as a reference for others in case of collection like
if (value instanceof Iterable) {
value = ((Iterable<?>) value).iterator().next();
}
// handle DBRef value
if (value instanceof DBRef) {
return ReferenceCollection.fromDBRef((DBRef) value);
}
String collection = mappingContext.getRequiredPersistentEntity(property.getAssociationTargetType()).getCollection();
if (value instanceof Document) {
Document documentPointer = (Document) value;
if (property.isDocumentReference()) {
ParameterBindingContext bindingContext = bindingContext(property, value, spELContext);
DocumentReference documentReference = property.getDocumentReference();
String targetDatabase = parseValueOrGet(documentReference.db(), bindingContext,
() -> documentPointer.get("db", String.class));
String targetCollection = parseValueOrGet(documentReference.collection(), bindingContext,
() -> documentPointer.get("collection", collection));
return new ReferenceCollection(targetDatabase, targetCollection);
}
return new ReferenceCollection(documentPointer.getString("db"), documentPointer.get("collection", collection));
}
if (property.isDocumentReference()) {
ParameterBindingContext bindingContext = bindingContext(property, value, spELContext);
DocumentReference documentReference = property.getDocumentReference();
String targetDatabase = parseValueOrGet(documentReference.db(), bindingContext, () -> null);
String targetCollection = parseValueOrGet(documentReference.collection(), bindingContext, () -> collection);
return new ReferenceCollection(targetDatabase, targetCollection);
}
return new ReferenceCollection(null, collection);
}
/**
* Use the given {@link ParameterBindingContext} to compute potential expressions against the value.
*
* @param value must not be {@literal null}.
* @param bindingContext must not be {@literal null}.
* @param defaultValue
* @param <T>
* @return can be {@literal null}.
*/
@Nullable
@SuppressWarnings("unchecked")
private <T> T parseValueOrGet(String value, ParameterBindingContext bindingContext, Supplier<T> defaultValue) {
if (!StringUtils.hasText(value)) {
return defaultValue.get();
}
// parameter binding requires a document, since we do not have one, construct it.
if (!BsonUtils.isJsonDocument(value) && value.contains("?#{")) {
String s = "{ 'target-value' : " + value + "}";
T evaluated = (T) codec.decode(s, bindingContext).get("target-value");
return evaluated != null ? evaluated : defaultValue.get();
}
if (BsonUtils.isJsonDocument(value)) {
return (T) codec.decode(value, bindingContext);
}
T evaluated = (T) bindingContext.evaluateExpression(value);
return evaluated != null ? evaluated : defaultValue.get();
}
ParameterBindingContext bindingContext(MongoPersistentProperty property, Object source, SpELContext spELContext) {
return new ParameterBindingContext(valueProviderFor(source), spELContext.getParser(),
() -> evaluationContextFor(property, source, spELContext));
}
ValueProvider valueProviderFor(Object source) {
return (index) -> {
if (source instanceof Document) {
return Streamable.of(((Document) source).values()).toList().get(index);
}
return source;
};
}
EvaluationContext evaluationContextFor(MongoPersistentProperty property, Object source, SpELContext spELContext) {
EvaluationContext ctx = spELContext.getEvaluationContext(source);
ctx.setVariable("target", source);
ctx.setVariable(property.getName(), source);
return ctx;
}
/**
* Compute the query to retrieve linked documents.
*
* @param property must not be {@literal null}.
* @param value must not be {@literal null}.
* @param spELContext must not be {@literal null}.
* @return never {@literal null}.
*/
@SuppressWarnings("unchecked")
DocumentReferenceQuery computeFilter(MongoPersistentProperty property, Object value, SpELContext spELContext) {
DocumentReference documentReference = property.isDocumentReference() ? property.getDocumentReference()
: ReferenceEmulatingDocumentReference.INSTANCE;
String lookup = documentReference.lookup();
Document sort = parseValueOrGet(documentReference.sort(), bindingContext(property, value, spELContext),
() -> new Document());
if (property.isCollectionLike() && value instanceof Collection) {
List<Document> ors = new ArrayList<>();
for (Object entry : (Collection<Object>) value) {
Document decoded = codec.decode(lookup, bindingContext(property, entry, spELContext));
ors.add(decoded);
}
return new ListDocumentReferenceQuery(new Document("$or", ors), sort);
}
if (property.isMap() && value instanceof Map) {
Map<Object, Document> filterMap = new LinkedHashMap<>();
for (Entry<Object, Object> entry : ((Map<Object, Object>) value).entrySet()) {
Document decoded = codec.decode(lookup, bindingContext(property, entry.getValue(), spELContext));
filterMap.put(entry.getKey(), decoded);
}
return new MapDocumentReferenceQuery(new Document("$or", filterMap.values()), sort, filterMap);
}
return new SingleDocumentReferenceQuery(codec.decode(lookup, bindingContext(property, value, spELContext)), sort);
}
enum ReferenceEmulatingDocumentReference implements DocumentReference {
INSTANCE;
@Override
public Class<? extends Annotation> annotationType() {
return DocumentReference.class;
}
@Override
public String db() {
return "";
}
@Override
public String collection() {
return "";
}
@Override
public String lookup() {
return "{ '_id' : ?#{#target} }";
}
@Override
public String sort() {
return "";
}
@Override
public boolean lazy() {
return false;
}
}
/**
* {@link DocumentReferenceQuery} implementation fetching a single {@link Document}.
*/
static class SingleDocumentReferenceQuery implements DocumentReferenceQuery {
private final Document query;
private final Document sort;
public SingleDocumentReferenceQuery(Document query, Document sort) {
this.query = query;
this.sort = sort;
}
@Override
public Bson getQuery() {
return query;
}
@Override
public Document getSort() {
return sort;
}
@Override
public Iterable<Document> apply(MongoCollection<Document> collection) {
Document result = collection.find(getQuery()).sort(getSort()).limit(1).first();
return result != null ? Collections.singleton(result) : Collections.emptyList();
}
}
/**
* {@link DocumentReferenceQuery} implementation to retrieve linked {@link Document documents} stored inside a
* {@link Map} structure. Restores the original map order by matching individual query documents against the actual
* values.
*/
static class MapDocumentReferenceQuery implements DocumentReferenceQuery {
private final Document query;
private final Document sort;
private final Map<Object, Document> filterOrderMap;
public MapDocumentReferenceQuery(Document query, Document sort, Map<Object, Document> filterOrderMap) {
this.query = query;
this.sort = sort;
this.filterOrderMap = filterOrderMap;
}
@Override
public Bson getQuery() {
return query;
}
@Override
public Bson getSort() {
return sort;
}
@Override
public Iterable<Document> restoreOrder(Iterable<Document> documents) {
Map<String, Object> targetMap = new LinkedHashMap<>();
List<Document> collected = documents instanceof List ? (List<Document>) documents
: Streamable.of(documents).toList();
for (Entry<Object, Document> filterMapping : filterOrderMap.entrySet()) {
Optional<Document> first = collected.stream()
.filter(it -> it.entrySet().containsAll(filterMapping.getValue().entrySet())).findFirst();
targetMap.put(filterMapping.getKey().toString(), first.orElse(null));
}
return Collections.singleton(new Document(targetMap));
}
}
/**
* {@link DocumentReferenceQuery} implementation to retrieve linked {@link Document documents} stored inside a
* {@link Collection} like structure. Restores the original order by matching individual query documents against the
* actual values.
*/
static class ListDocumentReferenceQuery implements DocumentReferenceQuery {
private final Document query;
private final Document sort;
public ListDocumentReferenceQuery(Document query, Document sort) {
this.query = query;
this.sort = sort;
}
@Override
public Iterable<Document> restoreOrder(Iterable<Document> documents) {
List<Document> target = documents instanceof List ? (List<Document>) documents
: Streamable.of(documents).toList();
if (!sort.isEmpty() || !query.containsKey("$or")) {
return target;
}
List<Document> ors = query.get("$or", List.class);
return target.stream().sorted((o1, o2) -> compareAgainstReferenceIndex(ors, o1, o2)).collect(Collectors.toList());
}
public Document getQuery() {
return query;
}
@Override
public Document getSort() {
return sort;
}
int compareAgainstReferenceIndex(List<Document> referenceList, Document document1, Document document2) {
for (Document document : referenceList) {
Set<Entry<String, Object>> entries = document.entrySet();
if (document1.entrySet().containsAll(entries)) {
return -1;
}
if (document2.entrySet().containsAll(entries)) {
return 1;
}
}
return referenceList.size();
}
}
/**
* The function that can execute a given {@link DocumentReferenceQuery} within the {@link ReferenceCollection} to
* obtain raw results.
*/
@FunctionalInterface
interface LookupFunction {
/**
* @param referenceQuery never {@literal null}.
* @param referenceCollection never {@literal null}.
* @return never {@literal null}.
*/
Iterable<Document> apply(DocumentReferenceQuery referenceQuery, ReferenceCollection referenceCollection);
}
}

View File

@@ -1,119 +0,0 @@
/*
* Copyright 2021 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.convert;
import org.springframework.data.mapping.PersistentProperty;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.util.TypeInformation;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import com.mongodb.DBRef;
/**
* The {@link ReferenceResolver} allows to load and convert linked entities.
*
* @author Christoph Strobl
* @since 3.3
*/
@FunctionalInterface
public interface ReferenceResolver {
/**
* Resolve the association defined via the given property from a given source value. May return a
* {@link LazyLoadingProxy proxy instance} in case of a lazy loading association. The resolved value is assignable to
* {@link PersistentProperty#getType()}.
*
* @param property the association defining property.
* @param source the association source value.
* @param referenceLookupDelegate the lookup executing component.
* @param entityReader conversion function capable of constructing entities from raw source.
* @return can be {@literal null}.
*/
@Nullable
Object resolveReference(MongoPersistentProperty property, Object source,
ReferenceLookupDelegate referenceLookupDelegate, MongoEntityReader entityReader);
/**
* {@link ReferenceCollection} is a value object that contains information about the target database and collection
* name of an association.
*/
class ReferenceCollection {
@Nullable //
private final String database;
private final String collection;
/**
* @param database can be {@literal null} to indicate the configured default
* {@link MongoDatabaseFactory#getMongoDatabase() database} should be used.
* @param collection the target collection name. Must not be {@literal null}.
*/
public ReferenceCollection(@Nullable String database, String collection) {
Assert.hasText(collection, "Collection must not be empty or null!");
this.database = database;
this.collection = collection;
}
/**
* Create a new instance of {@link ReferenceCollection} from the given {@link DBRef}.
*
* @param dbRef must not be {@literal null}.
* @return new instance of {@link ReferenceCollection}.
*/
public static ReferenceCollection fromDBRef(DBRef dbRef) {
return new ReferenceCollection(dbRef.getDatabaseName(), dbRef.getCollectionName());
}
/**
* Get the target collection name.
*
* @return never {@literal null}.
*/
public String getCollection() {
return collection;
}
/**
* Get the target database name. If {@literal null} the default database should be used.
*
* @return can be {@literal null}.
*/
@Nullable
public String getDatabase() {
return database;
}
}
/**
* Domain type conversion callback interface that allows to read the {@code source} object into a mapped object.
*/
@FunctionalInterface
interface MongoEntityReader {
/**
* Read values from the given source into an object defined via the given {@link TypeInformation}.
*
* @param source never {@literal null}.
* @param typeInformation information about the desired target type.
* @return never {@literal null}.
*/
Object read(Object source, TypeInformation<?> typeInformation);
}
}

View File

@@ -132,11 +132,6 @@ public class UpdateMapper extends QueryMapper {
*/
@Override
protected Object delegateConvertToMongoType(Object source, @Nullable MongoPersistentEntity<?> entity) {
if(entity != null && entity.isUnwrapped()) {
return converter.convertToMongoType(source, entity);
}
return converter.convertToMongoType(source,
entity == null ? ClassTypeInformation.OBJECT : getTypeHintForEntity(source, entity));
}

View File

@@ -24,7 +24,7 @@ import org.springframework.data.geo.Point;
import org.springframework.lang.Nullable;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
@@ -34,10 +34,7 @@ import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.node.ArrayNode;
/**
* A Jackson {@link Module} to register custom {@link JsonDeserializer}s for GeoJSON types.
* <p />
* Use {@link #geoJsonModule()} to obtain a {@link Module} containing both {@link JsonSerializer serializers} and
* {@link JsonDeserializer deserializers}.
* A Jackson {@link Module} to register custom {@link JsonSerializer} and {@link JsonDeserializer}s for GeoJSON types.
*
* @author Christoph Strobl
* @author Oliver Gierke
@@ -50,87 +47,12 @@ public class GeoJsonModule extends SimpleModule {
public GeoJsonModule() {
registerDeserializersIn(this);
// TODO: add serializers as of next major version (4.0).
}
/**
* Obtain a {@link Module} containing {@link JsonDeserializer deserializers} for the following {@link GeoJson} types:
* <ul>
* <li>{@link GeoJsonPoint}</li>
* <li>{@link GeoJsonMultiPoint}</li>
* <li>{@link GeoJsonLineString}</li>
* <li>{@link GeoJsonMultiLineString}</li>
* <li>{@link GeoJsonPolygon}</li>
* <li>{@link GeoJsonMultiPolygon}</li>
* </ul>
*
* @return a {@link Module} containing {@link JsonDeserializer deserializers} for {@link GeoJson} types.
* @since 3.2
*/
public static Module deserializers() {
SimpleModule module = new SimpleModule("Spring Data MongoDB GeoJson - Deserializers",
new Version(3, 2, 0, null, "org.springframework.data", "spring-data-mongodb-geojson"));
registerDeserializersIn(module);
return module;
}
/**
* Obtain a {@link Module} containing {@link JsonSerializer serializers} for the following {@link GeoJson} types:
* <ul>
* <li>{@link GeoJsonPoint}</li>
* <li>{@link GeoJsonMultiPoint}</li>
* <li>{@link GeoJsonLineString}</li>
* <li>{@link GeoJsonMultiLineString}</li>
* <li>{@link GeoJsonPolygon}</li>
* <li>{@link GeoJsonMultiPolygon}</li>
* </ul>
*
* @return a {@link Module} containing {@link JsonSerializer serializers} for {@link GeoJson} types.
* @since 3.2
*/
public static Module serializers() {
SimpleModule module = new SimpleModule("Spring Data MongoDB GeoJson - Serializers",
new Version(3, 2, 0, null, "org.springframework.data", "spring-data-mongodb-geojson"));
GeoJsonSerializersModule.registerSerializersIn(module);
return module;
}
/**
* Obtain a {@link Module} containing {@link JsonSerializer serializers} and {@link JsonDeserializer deserializers}
* for the following {@link GeoJson} types:
* <ul>
* <li>{@link GeoJsonPoint}</li>
* <li>{@link GeoJsonMultiPoint}</li>
* <li>{@link GeoJsonLineString}</li>
* <li>{@link GeoJsonMultiLineString}</li>
* <li>{@link GeoJsonPolygon}</li>
* <li>{@link GeoJsonMultiPolygon}</li>
* </ul>
*
* @return a {@link Module} containing {@link JsonSerializer serializers} and {@link JsonDeserializer deserializers}
* for {@link GeoJson} types.
* @since 3.2
*/
public static Module geoJsonModule() {
SimpleModule module = new SimpleModule("Spring Data MongoDB GeoJson",
new Version(3, 2, 0, null, "org.springframework.data", "spring-data-mongodb-geojson"));
GeoJsonSerializersModule.registerSerializersIn(module);
registerDeserializersIn(module);
return module;
}
private static void registerDeserializersIn(SimpleModule module) {
module.addDeserializer(GeoJsonPoint.class, new GeoJsonPointDeserializer());
module.addDeserializer(GeoJsonMultiPoint.class, new GeoJsonMultiPointDeserializer());
module.addDeserializer(GeoJsonLineString.class, new GeoJsonLineStringDeserializer());
module.addDeserializer(GeoJsonMultiLineString.class, new GeoJsonMultiLineStringDeserializer());
module.addDeserializer(GeoJsonPolygon.class, new GeoJsonPolygonDeserializer());
module.addDeserializer(GeoJsonMultiPolygon.class, new GeoJsonMultiPolygonDeserializer());
addDeserializer(GeoJsonPoint.class, new GeoJsonPointDeserializer());
addDeserializer(GeoJsonMultiPoint.class, new GeoJsonMultiPointDeserializer());
addDeserializer(GeoJsonLineString.class, new GeoJsonLineStringDeserializer());
addDeserializer(GeoJsonMultiLineString.class, new GeoJsonMultiLineStringDeserializer());
addDeserializer(GeoJsonPolygon.class, new GeoJsonPolygonDeserializer());
addDeserializer(GeoJsonMultiPolygon.class, new GeoJsonMultiPolygonDeserializer());
}
/**
@@ -145,7 +67,8 @@ public class GeoJsonModule extends SimpleModule {
*/
@Nullable
@Override
public T deserialize(@Nullable JsonParser jp, @Nullable DeserializationContext ctxt) throws IOException {
public T deserialize(@Nullable JsonParser jp, @Nullable DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = jp.readValueAsTree();
JsonNode coordinates = node.get("coordinates");
@@ -211,7 +134,7 @@ public class GeoJsonModule extends SimpleModule {
return Collections.emptyList();
}
List<Point> points = new ArrayList<>(node.size());
List<Point> points = new ArrayList<Point>(node.size());
for (JsonNode coordinatePair : node) {
if (coordinatePair.isArray()) {
@@ -222,7 +145,7 @@ public class GeoJsonModule extends SimpleModule {
}
protected GeoJsonLineString toLineString(ArrayNode node) {
return new GeoJsonLineString(toPoints(node));
return new GeoJsonLineString(toPoints((ArrayNode) node));
}
}
@@ -336,7 +259,7 @@ public class GeoJsonModule extends SimpleModule {
@Override
protected GeoJsonMultiLineString doDeserialize(ArrayNode coordinates) {
List<GeoJsonLineString> lines = new ArrayList<>(coordinates.size());
List<GeoJsonLineString> lines = new ArrayList<GeoJsonLineString>(coordinates.size());
for (JsonNode lineString : coordinates) {
if (lineString.isArray()) {
@@ -413,7 +336,7 @@ public class GeoJsonModule extends SimpleModule {
@Override
protected GeoJsonMultiPolygon doDeserialize(ArrayNode coordinates) {
List<GeoJsonPolygon> polygones = new ArrayList<>(coordinates.size());
List<GeoJsonPolygon> polygones = new ArrayList<GeoJsonPolygon>(coordinates.size());
for (JsonNode polygon : coordinates) {
for (JsonNode ring : polygon) {

View File

@@ -1,313 +0,0 @@
/*
* Copyright 2021 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.geo;
import java.io.IOException;
import org.springframework.data.geo.Point;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
/**
* A Jackson {@link Module} to register custom {@link JsonSerializer}s for GeoJSON types.
*
* @author Bjorn Harvold
* @author Christoph Strobl
* @since 3.2
*/
class GeoJsonSerializersModule extends SimpleModule {
private static final long serialVersionUID = 1340494654898895610L;
GeoJsonSerializersModule() {
registerSerializersIn(this);
}
static void registerSerializersIn(SimpleModule module) {
module.addSerializer(GeoJsonPoint.class, new GeoJsonPointSerializer());
module.addSerializer(GeoJsonMultiPoint.class, new GeoJsonMultiPointSerializer());
module.addSerializer(GeoJsonLineString.class, new GeoJsonLineStringSerializer());
module.addSerializer(GeoJsonMultiLineString.class, new GeoJsonMultiLineStringSerializer());
module.addSerializer(GeoJsonPolygon.class, new GeoJsonPolygonSerializer());
module.addSerializer(GeoJsonMultiPolygon.class, new GeoJsonMultiPolygonSerializer());
}
/**
* @param <T>
* @author Christoph Strobl
*/
private static abstract class GeoJsonSerializer<T extends GeoJson<? extends Iterable>> extends JsonSerializer<T> {
/*
* (non-Javadoc)
* @see com.fasterxml.jackson.databind.JsonSerializer#serialize(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider)
*/
@Override
public void serialize(T shape, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("type", shape.getType());
jsonGenerator.writeArrayFieldStart("coordinates");
doSerialize(shape, jsonGenerator);
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
}
/**
* Perform the actual serialization given the {@literal shape} as {@link GeoJson}.
*
* @param shape
* @param jsonGenerator
* @return
*/
protected abstract void doSerialize(T shape, JsonGenerator jsonGenerator) throws IOException;
/**
* Write a {@link Point} as array. <br />
* {@code [10.0, 20.0]}
*
* @param point
* @param jsonGenerator
* @throws IOException
*/
protected void writePoint(Point point, JsonGenerator jsonGenerator) throws IOException {
jsonGenerator.writeStartArray();
writeRawCoordinates(point, jsonGenerator);
jsonGenerator.writeEndArray();
}
/**
* Write the {@link Point} coordinates. <br />
* {@code 10.0, 20.0}
*
* @param point
* @param jsonGenerator
* @throws IOException
*/
protected void writeRawCoordinates(Point point, JsonGenerator jsonGenerator) throws IOException {
jsonGenerator.writeNumber(point.getX());
jsonGenerator.writeNumber(point.getY());
}
/**
* Write an {@link Iterable} of {@link Point} as array. <br />
* {@code [ [10.0, 20.0], [30.0, 40.0], [50.0, 60.0] ]}
*
* @param points
* @param jsonGenerator
* @throws IOException
*/
protected void writeLine(Iterable<Point> points, JsonGenerator jsonGenerator) throws IOException {
jsonGenerator.writeStartArray();
writeRawLine(points, jsonGenerator);
jsonGenerator.writeEndArray();
}
/**
* Write an {@link Iterable} of {@link Point}. <br />
* {@code [10.0, 20.0], [30.0, 40.0], [50.0, 60.0]}
*
* @param points
* @param jsonGenerator
* @throws IOException
*/
protected void writeRawLine(Iterable<Point> points, JsonGenerator jsonGenerator) throws IOException {
for (Point point : points) {
writePoint(point, jsonGenerator);
}
}
}
/**
* {@link JsonSerializer} converting {@link GeoJsonPoint} to:
*
* <pre>
* <code>
* { "type": "Point", "coordinates": [10.0, 20.0] }
* </code>
* </pre>
*
* @author Bjorn Harvold
* @author Christoph Strobl
* @since 3.2
*/
static class GeoJsonPointSerializer extends GeoJsonSerializer<GeoJsonPoint> {
@Override
protected void doSerialize(GeoJsonPoint value, JsonGenerator jsonGenerator) throws IOException {
writeRawCoordinates(value, jsonGenerator);
}
}
/**
* {@link JsonSerializer} converting {@link GeoJsonLineString} to:
*
* <pre>
* <code>
* {
* "type": "LineString",
* "coordinates": [
* [10.0, 20.0], [30.0, 40.0], [50.0, 60.0]
* ]
* }
* </code>
* </pre>
*
* @author Bjorn Harvold
* @author Christoph Strobl
* @since 3.2
*/
static class GeoJsonLineStringSerializer extends GeoJsonSerializer<GeoJsonLineString> {
@Override
protected void doSerialize(GeoJsonLineString value, JsonGenerator jsonGenerator) throws IOException {
writeRawLine(value.getCoordinates(), jsonGenerator);
}
}
/**
* {@link JsonSerializer} converting {@link GeoJsonMultiPoint} to:
*
* <pre>
* <code>
* {
* "type": "MultiPoint",
* "coordinates": [
* [10.0, 20.0], [30.0, 40.0], [50.0, 60.0]
* ]
* }
* </code>
* </pre>
*
* @author Bjorn Harvold
* @author Christoph Strobl
* @since 3.2
*/
static class GeoJsonMultiPointSerializer extends GeoJsonSerializer<GeoJsonMultiPoint> {
@Override
protected void doSerialize(GeoJsonMultiPoint value, JsonGenerator jsonGenerator) throws IOException {
writeRawLine(value.getCoordinates(), jsonGenerator);
}
}
/**
* {@link JsonSerializer} converting {@link GeoJsonMultiLineString} to:
*
* <pre>
* <code>
* {
* "type": "MultiLineString",
* "coordinates": [
* [ [10.0, 20.0], [30.0, 40.0] ],
* [ [50.0, 60.0] , [70.0, 80.0] ]
* ]
* }
* </code>
* </pre>
*
* @author Bjorn Harvold
* @author Christoph Strobl
* @since 3.2
*/
static class GeoJsonMultiLineStringSerializer extends GeoJsonSerializer<GeoJsonMultiLineString> {
@Override
protected void doSerialize(GeoJsonMultiLineString value, JsonGenerator jsonGenerator) throws IOException {
for (GeoJsonLineString lineString : value.getCoordinates()) {
writeLine(lineString.getCoordinates(), jsonGenerator);
}
}
}
/**
* {@link JsonSerializer} converting {@link GeoJsonPolygon} to:
*
* <pre>
* <code>
* {
* "type": "Polygon",
* "coordinates": [
* [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ]
* ]
* }
* </code>
* </pre>
*
* @author Bjorn Harvold
* @author Christoph Strobl
* @since 3.2
*/
static class GeoJsonPolygonSerializer extends GeoJsonSerializer<GeoJsonPolygon> {
@Override
protected void doSerialize(GeoJsonPolygon value, JsonGenerator jsonGenerator) throws IOException {
for (GeoJsonLineString lineString : value.getCoordinates()) {
writeLine(lineString.getCoordinates(), jsonGenerator);
}
}
}
/**
* {@link JsonSerializer} converting {@link GeoJsonMultiPolygon} to:
*
* <pre>
* <code>
* {
* "type": "MultiPolygon",
* "coordinates": [
* [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]],
* [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]],
* [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]]
* ]
* }
* </code>
* </pre>
*
* @author Bjorn Harvold
* @author Christoph Strobl
* @since 3.2
*/
static class GeoJsonMultiPolygonSerializer extends GeoJsonSerializer<GeoJsonMultiPolygon> {
@Override
protected void doSerialize(GeoJsonMultiPolygon value, JsonGenerator jsonGenerator) throws IOException {
for (GeoJsonPolygon polygon : value.getCoordinates()) {
jsonGenerator.writeStartArray();
for (GeoJsonLineString lineString : polygon.getCoordinates()) {
writeLine(lineString.getCoordinates(), jsonGenerator);
}
jsonGenerator.writeEndArray();
}
}
}
}

View File

@@ -29,17 +29,7 @@ import org.springframework.util.ObjectUtils;
public final class IndexField {
enum Type {
GEO, TEXT, DEFAULT,
/**
* @since 2.2
*/
HASH,
/**
* @since 3.3
*/
WILDCARD;
GEO, TEXT, DEFAULT, HASH;
}
private final String key;
@@ -58,7 +48,7 @@ public final class IndexField {
if (Type.GEO.equals(type) || Type.TEXT.equals(type)) {
Assert.isNull(direction, "Geo/Text indexes must not have a direction!");
} else {
if (!(Type.HASH.equals(type) || Type.WILDCARD.equals(type))) {
if (!Type.HASH.equals(type)) {
Assert.notNull(direction, "Default indexes require a direction");
}
}
@@ -87,18 +77,6 @@ public final class IndexField {
return new IndexField(key, null, Type.HASH);
}
/**
* Creates a {@literal wildcard} {@link IndexField} for the given key. The {@code key} must follow the
* {@code fieldName.$**} notation.
*
* @param key must not be {@literal null} or empty.
* @return new instance of {@link IndexField}.
* @since 3.3
*/
static IndexField wildcard(String key) {
return new IndexField(key, null, Type.WILDCARD);
}
/**
* Creates a geo {@link IndexField} for the given key.
*
@@ -164,16 +142,6 @@ public final class IndexField {
return Type.HASH.equals(type);
}
/**
* Returns whether the {@link IndexField} is contains a {@literal wildcard} expression.
*
* @return {@literal true} if {@link IndexField} contains a wildcard {@literal $**}.
* @since 3.3
*/
public boolean isWildcard() {
return Type.WILDCARD.equals(type);
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)

View File

@@ -55,7 +55,6 @@ public class IndexInfo {
private @Nullable Duration expireAfter;
private @Nullable String partialFilterExpression;
private @Nullable Document collation;
private @Nullable Document wildcardProjection;
public IndexInfo(List<IndexField> indexFields, String name, boolean unique, boolean sparse, String language) {
@@ -100,8 +99,6 @@ public class IndexInfo {
if (ObjectUtils.nullSafeEquals("hashed", value)) {
indexFields.add(IndexField.hashed(key));
} else if (key.endsWith("$**")) {
indexFields.add(IndexField.wildcard(key));
} else {
Double keyValue = new Double(value.toString());
@@ -134,10 +131,6 @@ public class IndexInfo {
info.expireAfter = Duration.ofSeconds(NumberUtils.convertNumberToTargetClass(expireAfterSeconds, Long.class));
}
if (sourceDocument.containsKey("wildcardProjection")) {
info.wildcardProjection = sourceDocument.get("wildcardProjection", Document.class);
}
return info;
}
@@ -223,16 +216,6 @@ public class IndexInfo {
return Optional.ofNullable(collation);
}
/**
* Get {@literal wildcardProjection} information.
*
* @return {@link Optional#empty() empty} if not set.
* @since 3.3
*/
public Optional<Document> getWildcardProjection() {
return Optional.ofNullable(wildcardProjection);
}
/**
* Get the duration after which documents within the index expire.
*
@@ -251,14 +234,6 @@ public class IndexInfo {
return getIndexFields().stream().anyMatch(IndexField::isHashed);
}
/**
* @return {@literal true} if a wildcard index field is present.
* @since 3.3
*/
public boolean isWildcard() {
return getIndexFields().stream().anyMatch(IndexField::isWildcard);
}
@Override
public String toString() {
@@ -328,5 +303,4 @@ public class IndexInfo {
}
return true;
}
}

View File

@@ -15,8 +15,6 @@
*/
package org.springframework.data.mongodb.core.index;
import org.springframework.lang.Nullable;
/**
* Provider interface to obtain {@link IndexOperations} by MongoDB collection name.
*
@@ -28,22 +26,10 @@ import org.springframework.lang.Nullable;
public interface IndexOperationsProvider {
/**
* Returns the operations that can be performed on indexes.
* Returns the operations that can be performed on indexes
*
* @param collectionName name of the MongoDB collection, must not be {@literal null}.
* @return index operations on the named collection
*/
default IndexOperations indexOps(String collectionName) {
return indexOps(collectionName, null);
}
/**
* Returns the operations that can be performed on indexes.
*
* @param collectionName name of the MongoDB collection, must not be {@literal null}.
* @param type the type used for field mapping. Can be {@literal null}.
* @return index operations on the named collection
* @since 3.2
*/
IndexOperations indexOps(String collectionName, @Nullable Class<?> type);
IndexOperations indexOps(String collectionName);
}

View File

@@ -46,9 +46,7 @@ import org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.core.query.Collation;
import org.springframework.data.mongodb.util.BsonUtils;
import org.springframework.data.mongodb.util.DotPath;
import org.springframework.data.spel.EvaluationContextProvider;
import org.springframework.data.util.TypeInformation;
import org.springframework.expression.EvaluationContext;
@@ -119,12 +117,9 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
Assert.notNull(document, () -> String
.format("Entity %s is not a collection root. Make sure to annotate it with @Document!", root.getName()));
verifyWildcardIndexedProjection(root);
List<IndexDefinitionHolder> indexInformation = new ArrayList<>();
String collection = root.getCollection();
indexInformation.addAll(potentiallyCreateCompoundIndexDefinitions("", collection, root));
indexInformation.addAll(potentiallyCreateWildcardIndexDefinitions("", collection, root));
indexInformation.addAll(potentiallyCreateTextIndexDefinition(root, collection));
root.doWithProperties((PropertyHandler<MongoPersistentProperty>) property -> this
@@ -135,32 +130,13 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
return indexInformation;
}
private void verifyWildcardIndexedProjection(MongoPersistentEntity<?> entity) {
entity.doWithAll(it -> {
if (it.isAnnotationPresent(WildcardIndexed.class)) {
WildcardIndexed indexed = it.getRequiredAnnotation(WildcardIndexed.class);
if (!ObjectUtils.isEmpty(indexed.wildcardProjection())) {
throw new MappingException(String.format(
"WildcardIndexed.wildcardProjection cannot be used on nested paths. Offending property: %s.%s",
entity.getName(), it.getName()));
}
}
});
}
private void potentiallyAddIndexForProperty(MongoPersistentEntity<?> root, MongoPersistentProperty persistentProperty,
List<IndexDefinitionHolder> indexes, CycleGuard guard) {
try {
if (persistentProperty.isEntity()) {
indexes.addAll(resolveIndexForEntity(mappingContext.getPersistentEntity(persistentProperty),
persistentProperty.isUnwrapped() ? "" : persistentProperty.getFieldName(), Path.of(persistentProperty),
root.getCollection(), guard));
indexes.addAll(resolveIndexForClass(persistentProperty.getTypeInformation().getActualType(),
persistentProperty.getFieldName(), Path.of(persistentProperty), root.getCollection(), guard));
}
List<IndexDefinitionHolder> indexDefinitions = createIndexDefinitionHolderForProperty(
@@ -184,18 +160,13 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
* @return List of {@link IndexDefinitionHolder} representing indexes for given type and its referenced property
* types. Will never be {@code null}.
*/
private List<IndexDefinitionHolder> resolveIndexForClass(TypeInformation<?> type, String dotPath, Path path,
String collection, CycleGuard guard) {
private List<IndexDefinitionHolder> resolveIndexForClass(final TypeInformation<?> type, final String dotPath,
final Path path, final String collection, final CycleGuard guard) {
return resolveIndexForEntity(mappingContext.getRequiredPersistentEntity(type), dotPath, path, collection, guard);
}
MongoPersistentEntity<?> entity = mappingContext.getRequiredPersistentEntity(type);
private List<IndexDefinitionHolder> resolveIndexForEntity(MongoPersistentEntity<?> entity, String dotPath, Path path,
String collection, CycleGuard guard) {
List<IndexDefinitionHolder> indexInformation = new ArrayList<>();
final List<IndexDefinitionHolder> indexInformation = new ArrayList<>();
indexInformation.addAll(potentiallyCreateCompoundIndexDefinitions(dotPath, collection, entity));
indexInformation.addAll(potentiallyCreateWildcardIndexDefinitions(dotPath, collection, entity));
entity.doWithProperties((PropertyHandler<MongoPersistentProperty>) property -> this
.guardAndPotentiallyAddIndexForProperty(property, dotPath, path, collection, indexInformation, guard));
@@ -208,26 +179,22 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
private void guardAndPotentiallyAddIndexForProperty(MongoPersistentProperty persistentProperty, String dotPath,
Path path, String collection, List<IndexDefinitionHolder> indexes, CycleGuard guard) {
DotPath propertyDotPath = DotPath.from(dotPath);
if (!persistentProperty.isUnwrapped()) {
propertyDotPath = propertyDotPath.append(persistentProperty.getFieldName());
}
String propertyDotPath = (StringUtils.hasText(dotPath) ? dotPath + "." : "") + persistentProperty.getFieldName();
Path propertyPath = path.append(persistentProperty);
guard.protect(persistentProperty, propertyPath);
if (persistentProperty.isEntity()) {
try {
indexes.addAll(resolveIndexForEntity(mappingContext.getPersistentEntity(persistentProperty),
propertyDotPath.toString(), propertyPath, collection, guard));
indexes.addAll(resolveIndexForClass(persistentProperty.getTypeInformation().getActualType(), propertyDotPath,
propertyPath, collection, guard));
} catch (CyclicPropertyReferenceException e) {
LOGGER.info(e.getMessage());
}
}
List<IndexDefinitionHolder> indexDefinitions = createIndexDefinitionHolderForProperty(propertyDotPath.toString(),
collection, persistentProperty);
List<IndexDefinitionHolder> indexDefinitions = createIndexDefinitionHolderForProperty(propertyDotPath, collection,
persistentProperty);
if (!indexDefinitions.isEmpty()) {
indexes.addAll(indexDefinitions);
@@ -239,13 +206,6 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
List<IndexDefinitionHolder> indices = new ArrayList<>(2);
if (persistentProperty.isUnwrapped() && (persistentProperty.isAnnotationPresent(Indexed.class)
|| persistentProperty.isAnnotationPresent(HashIndexed.class)
|| persistentProperty.isAnnotationPresent(GeoSpatialIndexed.class))) {
throw new InvalidDataAccessApiUsageException(
String.format("Index annotation not allowed on unwrapped object for path '%s'.", dotPath));
}
if (persistentProperty.isAnnotationPresent(Indexed.class)) {
indices.add(createIndexDefinition(dotPath, collection, persistentProperty));
} else if (persistentProperty.isAnnotationPresent(GeoSpatialIndexed.class)) {
@@ -255,11 +215,6 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
if (persistentProperty.isAnnotationPresent(HashIndexed.class)) {
indices.add(createHashedIndexDefinition(dotPath, collection, persistentProperty));
}
if (persistentProperty.isAnnotationPresent(WildcardIndexed.class)) {
indices.add(createWildcardIndexDefinition(dotPath, collection,
persistentProperty.getRequiredAnnotation(WildcardIndexed.class),
mappingContext.getPersistentEntity(persistentProperty)));
}
return indices;
}
@@ -274,18 +229,6 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
return createCompoundIndexDefinitions(dotPath, collection, entity);
}
private List<IndexDefinitionHolder> potentiallyCreateWildcardIndexDefinitions(String dotPath, String collection,
MongoPersistentEntity<?> entity) {
if (!entity.isAnnotationPresent(WildcardIndexed.class)) {
return Collections.emptyList();
}
return Collections.singletonList(new IndexDefinitionHolder(dotPath,
createWildcardIndexDefinition(dotPath, collection, entity.getRequiredAnnotation(WildcardIndexed.class), entity),
collection));
}
private Collection<? extends IndexDefinitionHolder> potentiallyCreateTextIndexDefinition(
MongoPersistentEntity<?> root, String collection) {
@@ -311,7 +254,7 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
}
try {
appendTextIndexInformation(DotPath.empty(), Path.empty(), indexDefinitionBuilder, root,
appendTextIndexInformation("", Path.empty(), indexDefinitionBuilder, root,
new TextIndexIncludeOptions(IncludeStrategy.DEFAULT), new CycleGuard());
} catch (CyclicPropertyReferenceException e) {
LOGGER.info(e.getMessage());
@@ -332,8 +275,9 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
}
private void appendTextIndexInformation(DotPath dotPath, Path path, TextIndexDefinitionBuilder indexDefinitionBuilder,
MongoPersistentEntity<?> entity, TextIndexIncludeOptions includeOptions, CycleGuard guard) {
private void appendTextIndexInformation(final String dotPath, final Path path,
final TextIndexDefinitionBuilder indexDefinitionBuilder, final MongoPersistentEntity<?> entity,
final TextIndexIncludeOptions includeOptions, final CycleGuard guard) {
entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {
@@ -342,7 +286,7 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
guard.protect(persistentProperty, path);
if (persistentProperty.isExplicitLanguageProperty() && dotPath.isEmpty()) {
if (persistentProperty.isExplicitLanguageProperty() && !StringUtils.hasText(dotPath)) {
indexDefinitionBuilder.withLanguageOverride(persistentProperty.getFieldName());
}
@@ -350,7 +294,8 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
if (includeOptions.isForce() || indexed != null || persistentProperty.isEntity()) {
DotPath propertyDotPath = dotPath.append(persistentProperty.getFieldName());
String propertyDotPath = (StringUtils.hasText(dotPath) ? dotPath + "." : "")
+ persistentProperty.getFieldName();
Path propertyPath = path.append(persistentProperty);
@@ -363,7 +308,7 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
TextIndexIncludeOptions optionsForNestedType = includeOptions;
if (!IncludeStrategy.FORCE.equals(includeOptions.getStrategy()) && indexed != null) {
optionsForNestedType = new TextIndexIncludeOptions(IncludeStrategy.FORCE,
new TextIndexedFieldSpec(propertyDotPath.toString(), weight));
new TextIndexedFieldSpec(propertyDotPath, weight));
}
try {
@@ -376,7 +321,7 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
entity.getName()), e);
}
} else if (includeOptions.isForce() || indexed != null) {
indexDefinitionBuilder.onField(propertyDotPath.toString(), weight);
indexDefinitionBuilder.onField(propertyDotPath, weight);
}
}
@@ -444,32 +389,6 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
return new IndexDefinitionHolder(dotPath, indexDefinition, collection);
}
protected IndexDefinitionHolder createWildcardIndexDefinition(String dotPath, String collection,
WildcardIndexed index, @Nullable MongoPersistentEntity<?> entity) {
WildcardIndex indexDefinition = new WildcardIndex(dotPath);
if (StringUtils.hasText(index.wildcardProjection()) && ObjectUtils.isEmpty(dotPath)) {
indexDefinition.wildcardProjection(evaluateWildcardProjection(index.wildcardProjection(), entity));
}
if (!index.useGeneratedName()) {
indexDefinition.named(pathAwareIndexName(index.name(), dotPath, entity, null));
}
if (StringUtils.hasText(index.partialFilter())) {
indexDefinition.partial(evaluatePartialFilter(index.partialFilter(), entity));
}
if (StringUtils.hasText(index.collation())) {
indexDefinition.collation(evaluateCollation(index.collation(), entity));
} else if (entity != null && entity.hasCollation()) {
indexDefinition.collation(entity.getCollation());
}
return new IndexDefinitionHolder(dotPath, indexDefinition, collection);
}
private org.bson.Document resolveCompoundIndexKeyFromStringDefinition(String dotPath, String keyDefinitionString,
PersistentEntity<?, ?> entity) {
@@ -563,7 +482,7 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
return new IndexDefinitionHolder(dotPath, indexDefinition, collection);
}
private PartialIndexFilter evaluatePartialFilter(String filterExpression, PersistentEntity<?, ?> entity) {
private PartialIndexFilter evaluatePartialFilter(String filterExpression, PersistentEntity<?,?> entity) {
Object result = evaluate(filterExpression, getEvaluationContextForProperty(entity));
@@ -574,32 +493,6 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
return PartialIndexFilter.of(BsonUtils.parse(filterExpression, null));
}
private org.bson.Document evaluateWildcardProjection(String projectionExpression, PersistentEntity<?, ?> entity) {
Object result = evaluate(projectionExpression, getEvaluationContextForProperty(entity));
if (result instanceof org.bson.Document) {
return (org.bson.Document) result;
}
return BsonUtils.parse(projectionExpression, null);
}
private Collation evaluateCollation(String collationExpression, PersistentEntity<?, ?> entity) {
Object result = evaluate(collationExpression, getEvaluationContextForProperty(entity));
if (result instanceof org.bson.Document) {
return Collation.from((org.bson.Document) result);
}
if (result instanceof Collation) {
return (Collation) result;
}
if (result instanceof String) {
return Collation.parse(result.toString());
}
throw new IllegalStateException("Cannot parse collation " + result);
}
/**
* Creates {@link HashedIndex} wrapped in {@link IndexDefinitionHolder} out of {@link HashIndexed} for a given
@@ -740,7 +633,7 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
MongoPersistentProperty property = association.getInverse();
DotPath propertyDotPath = DotPath.from(path).append(property.getFieldName());
String propertyDotPath = (StringUtils.hasText(path) ? path + "." : "") + property.getFieldName();
if (property.isAnnotationPresent(GeoSpatialIndexed.class) || property.isAnnotationPresent(TextIndexed.class)) {
throw new MappingException(
@@ -748,8 +641,8 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
propertyDotPath));
}
List<IndexDefinitionHolder> indexDefinitions = createIndexDefinitionHolderForProperty(propertyDotPath.toString(),
collection, property);
List<IndexDefinitionHolder> indexDefinitions = createIndexDefinitionHolderForProperty(propertyDotPath, collection,
property);
if (!indexDefinitions.isEmpty()) {
indexes.addAll(indexDefinitions);
@@ -1089,11 +982,6 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver {
public org.bson.Document getIndexOptions() {
return indexDefinition.getIndexOptions();
}
@Override
public String toString() {
return "IndexDefinitionHolder{" + "indexKeys=" + getIndexKeys() + '}';
}
}
/**

View File

@@ -1,198 +0,0 @@
/*
* Copyright 2021 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.index;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.bson.Document;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* {@link WildcardIndex} is a specific {@link Index} that can be used to include all fields into an index based on the
* {@code $**" : 1} pattern on a root object (the one typically carrying the
* {@link org.springframework.data.mongodb.core.mapping.Document} annotation). On those it is possible to use
* {@link #wildcardProjectionInclude(String...)} and {@link #wildcardProjectionExclude(String...)} to define specific
* paths for in-/exclusion.
* <p />
* It can also be used to define an index on a specific field path and its subfields, e.g.
* {@code "path.to.field.$**" : 1}. <br />
* Note that {@literal wildcardProjections} are not allowed in this case.
* <p />
* <strong>LIMITATIONS</strong><br />
* <ul>
* <li>{@link #unique() Unique} and {@link #expire(long) ttl} options are not supported.</li>
* <li>Keys used for sharding must not be included</li>
* <li>Cannot be used to generate any type of geo index.</li>
* </ul>
*
* @author Christoph Strobl
* @see <a href= "https://docs.mongodb.com/manual/core/index-wildcard/">MongoDB Reference Documentation: Wildcard
* Indexes/</a>
* @since 3.3
*/
public class WildcardIndex extends Index {
private @Nullable String fieldName;
private final Map<String, Object> wildcardProjection = new LinkedHashMap<>();
/**
* Create a new instance of {@link WildcardIndex} using {@code $**}.
*/
public WildcardIndex() {}
/**
* Create a new instance of {@link WildcardIndex} for the given {@literal path}. If no {@literal path} is provided the
* index will be considered a root one using {@code $**}. <br />
* <strong>NOTE</strong> {@link #wildcardProjectionInclude(String...)}, {@link #wildcardProjectionExclude(String...)}
* can only be used for top level index definitions having an {@literal empty} or {@literal null} path.
*
* @param path can be {@literal null}. If {@literal null} all fields will be indexed.
*/
public WildcardIndex(@Nullable String path) {
this.fieldName = path;
}
/**
* Include the {@code _id} field in {@literal wildcardProjection}.
*
* @return this.
*/
public WildcardIndex includeId() {
wildcardProjection.put("_id", 1);
return this;
}
/**
* Set the index name to use.
*
* @param name
* @return this.
*/
@Override
public WildcardIndex named(String name) {
super.named(name);
return this;
}
/**
* Unique option is not supported.
*
* @throws UnsupportedOperationException not supported for wildcard indexes.
*/
@Override
public Index unique() {
throw new UnsupportedOperationException("Wildcard Index does not support 'unique'.");
}
/**
* ttl option is not supported.
*
* @throws UnsupportedOperationException not supported for wildcard indexes.
*/
@Override
public Index expire(long seconds) {
throw new UnsupportedOperationException("Wildcard Index does not support 'ttl'.");
}
/**
* ttl option is not supported.
*
* @throws UnsupportedOperationException not supported for wildcard indexes.
*/
@Override
public Index expire(long value, TimeUnit timeUnit) {
throw new UnsupportedOperationException("Wildcard Index does not support 'ttl'.");
}
/**
* ttl option is not supported.
*
* @throws UnsupportedOperationException not supported for wildcard indexes.
*/
@Override
public Index expire(Duration duration) {
throw new UnsupportedOperationException("Wildcard Index does not support 'ttl'.");
}
/**
* Add fields to be included from indexing via {@code wildcardProjection}. <br />
* This option is only allowed on {@link WildcardIndex#WildcardIndex() top level} wildcard indexes.
*
* @param paths must not be {@literal null}.
* @return this.
*/
public WildcardIndex wildcardProjectionInclude(String... paths) {
for (String path : paths) {
wildcardProjection.put(path, 1);
}
return this;
}
/**
* Add fields to be excluded from indexing via {@code wildcardProjection}. <br />
* This option is only allowed on {@link WildcardIndex#WildcardIndex() top level} wildcard indexes.
*
* @param paths must not be {@literal null}.
* @return this.
*/
public WildcardIndex wildcardProjectionExclude(String... paths) {
for (String path : paths) {
wildcardProjection.put(path, 0);
}
return this;
}
/**
* Set the fields to be in-/excluded from indexing via {@code wildcardProjection}. <br />
* This option is only allowed on {@link WildcardIndex#WildcardIndex() top level} wildcard indexes.
*
* @param includeExclude must not be {@literal null}.
* @return this.
*/
public WildcardIndex wildcardProjection(Map<String, Object> includeExclude) {
wildcardProjection.putAll(includeExclude);
return this;
}
private String getTargetFieldName() {
return StringUtils.hasText(fieldName) ? (fieldName + ".$**") : "$**";
}
@Override
public Document getIndexKeys() {
return new Document(getTargetFieldName(), 1);
}
@Override
public Document getIndexOptions() {
Document options = new Document(super.getIndexOptions());
if (!CollectionUtils.isEmpty(wildcardProjection)) {
options.put("wildcardProjection", new Document(wildcardProjection));
}
return options;
}
}

View File

@@ -1,130 +0,0 @@
/*
* Copyright 2021 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.index;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation for an entity or property that should be used as key for a
* <a href="https://docs.mongodb.com/manual/core/index-wildcard/">Wildcard Index</a>. <br />
* If placed on a {@link ElementType#TYPE type} that is a root level domain entity (one having an
* {@link org.springframework.data.mongodb.core.mapping.Document} annotation) will advise the index creator to create a
* wildcard index for it.
*
* <pre class="code">
*
* &#64;Document
* &#64;WildcardIndexed
* public class Product {
* ...
* }
*
* db.product.createIndex({ "$**" : 1 } , {})
* </pre>
*
* {@literal wildcardProjection} can be used to specify keys to in-/exclude in the index.
*
* <pre class="code">
*
* &#64;Document
* &#64;WildcardIndexed(wildcardProjection = "{ 'userMetadata.age' : 0 }")
* public class User {
* private &#64;Id String id;
* private UserMetadata userMetadata;
* }
*
*
* db.user.createIndex(
* { "$**" : 1 },
* { "wildcardProjection" :
* { "userMetadata.age" : 0 }
* }
* )
* </pre>
*
* Wildcard indexes can also be expressed by adding the annotation directly to the field. Please note that
* {@literal wildcardProjection} is not allowed on nested paths.
*
* <pre class="code">
* &#64;Document
* public class User {
*
* private &#64;Id String id;
*
* &#64;WildcardIndexed
* private UserMetadata userMetadata;
* }
*
*
* db.user.createIndex({ "userMetadata.$**" : 1 }, {})
* </pre>
*
* @author Christoph Strobl
* @since 3.3
*/
@Documented
@Target({ ElementType.TYPE, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface WildcardIndexed {
/**
* Index name either as plain value or as {@link org.springframework.expression.spel.standard.SpelExpression template
* expression}. <br />
* <br />
* The name will only be applied as is when defined on root level. For usage on nested or embedded structures the
* provided name will be prefixed with the path leading to the entity.
*
* @return empty by default.
*/
String name() default "";
/**
* If set to {@literal true} then MongoDB will ignore the given index name and instead generate a new name. Defaults
* to {@literal false}.
*
* @return {@literal false} by default.
*/
boolean useGeneratedName() default false;
/**
* Only index the documents in a collection that meet a specified {@link IndexFilter filter expression}. <br />
*
* @return empty by default.
* @see <a href=
* "https://docs.mongodb.com/manual/core/index-partial/">https://docs.mongodb.com/manual/core/index-partial/</a>
*/
String partialFilter() default "";
/**
* Explicitly specify sub fields to be in-/excluded as a {@link org.bson.Document#parse(String) prasable} String.
* <br />
* <strong>NOTE: </strong>Can only be applied on root level documents.
*
* @return empty by default.
*/
String wildcardProjection() default "";
/**
* Defines the collation to apply.
*
* @return an empty {@link String} by default.
*/
String collation() default "";
}

View File

@@ -164,8 +164,7 @@ public class BasicMongoPersistentEntity<T> extends BasicPersistentEntity<T, Mong
@Override
public org.springframework.data.mongodb.core.query.Collation getCollation() {
Object collationValue = collationExpression != null
? collationExpression.getValue(getEvaluationContext(null), String.class)
Object collationValue = collationExpression != null ? collationExpression.getValue(getEvaluationContext(null), String.class)
: this.collation;
if (collationValue == null) {

View File

@@ -41,14 +41,13 @@ import org.springframework.util.StringUtils;
* @author Thomas Darimont
* @author Christoph Strobl
* @author Mark Paluch
* @author Divya Srivastava
*/
public class BasicMongoPersistentProperty extends AnnotationBasedPersistentProperty<MongoPersistentProperty>
implements MongoPersistentProperty {
private static final Logger LOG = LoggerFactory.getLogger(BasicMongoPersistentProperty.class);
public static final String ID_FIELD_NAME = "_id";
private static final String ID_FIELD_NAME = "_id";
private static final String LANGUAGE_FIELD_NAME = "language";
private static final Set<Class<?>> SUPPORTED_ID_TYPES = new HashSet<Class<?>>();
private static final Set<String> SUPPORTED_ID_PROPERTY_NAMES = new HashSet<String>();
@@ -215,19 +214,6 @@ public class BasicMongoPersistentProperty extends AnnotationBasedPersistentPrope
return annotation != null ? annotation.order() : Integer.MAX_VALUE;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.mapping.MongoPersistentProperty#skipNullValues()
*/
@Override
public boolean writeNullValues() {
org.springframework.data.mongodb.core.mapping.Field annotation = findAnnotation(
org.springframework.data.mongodb.core.mapping.Field.class);
return annotation != null && annotation.write() == Field.Write.ALWAYS;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mapping.model.AbstractPersistentProperty#createAssociation()
@@ -245,15 +231,6 @@ public class BasicMongoPersistentProperty extends AnnotationBasedPersistentPrope
return isAnnotationPresent(DBRef.class);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.mapping.MongoPersistentProperty#isDocumentReference()
*/
@Override
public boolean isDocumentReference() {
return isAnnotationPresent(DocumentReference.class);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.mapping.MongoPersistentProperty#getDBRef()
@@ -263,16 +240,6 @@ public class BasicMongoPersistentProperty extends AnnotationBasedPersistentPrope
return findAnnotation(DBRef.class);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.mapping.MongoPersistentProperty#getDocumentReference()
*/
@Nullable
@Override
public DocumentReference getDocumentReference() {
return findAnnotation(DocumentReference.class);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.mapping.MongoPersistentProperty#isLanguageProperty()
@@ -299,5 +266,4 @@ public class BasicMongoPersistentProperty extends AnnotationBasedPersistentPrope
public boolean isTextScoreProperty() {
return isAnnotationPresent(TextScore.class);
}
}

View File

@@ -33,7 +33,6 @@ public class CachingMongoPersistentProperty extends BasicMongoPersistentProperty
private boolean dbRefResolved;
private @Nullable DBRef dbref;
private @Nullable String fieldName;
private @Nullable Boolean writeNullValues;
private @Nullable Class<?> fieldType;
private @Nullable Boolean usePropertyAccess;
private @Nullable Boolean isTransient;
@@ -91,20 +90,6 @@ public class CachingMongoPersistentProperty extends BasicMongoPersistentProperty
return this.fieldName;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.mapping.BasicMongoPersistentProperty#skipNullValues()
*/
@Override
public boolean writeNullValues() {
if (this.writeNullValues == null) {
this.writeNullValues = super.writeNullValues();
}
return this.writeNullValues;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.mapping.BasicMongoPersistentProperty#getFieldType()

View File

@@ -41,7 +41,7 @@ public @interface Document {
* The collection the document representing the entity is supposed to be stored in. If not configured, a default
* collection name will be derived from the type's name. The attribute supports SpEL expressions to dynamically
* calculate the collection to based on a per operation basis.
*
*
* @return the name of the collection to be used.
*/
@AliasFor("collection")
@@ -51,7 +51,7 @@ public @interface Document {
* The collection the document representing the entity is supposed to be stored in. If not configured, a default
* collection name will be derived from the type's name. The attribute supports SpEL expressions to dynamically
* calculate the collection to based on a per operation basis.
*
*
* @return the name of the collection to be used.
*/
@AliasFor("value")

View File

@@ -1,35 +0,0 @@
/*
* Copyright 2021 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.mapping;
/**
* A custom pointer to a linked document to be used along with {@link DocumentReference} for storing the linkage value.
*
* @author Christoph Strobl
* @since 3.3
*/
@FunctionalInterface
public interface DocumentPointer<T> {
/**
* The actual pointer value. This can be any simple type, like a {@link String} or {@link org.bson.types.ObjectId} or
* a {@link org.bson.Document} holding more information like the target collection, multiple fields forming the key,
* etc.
*
* @return the value stored in MongoDB and used for constructing the {@link DocumentReference#lookup() lookup query}.
*/
T getPointer();
}

View File

@@ -1,132 +0,0 @@
/*
* Copyright 2021 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.mapping;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.data.annotation.Reference;
import org.springframework.data.mongodb.MongoDatabaseFactory;
/**
* A {@link DocumentReference} allows referencing entities in MongoDB using a flexible schema. While the goal is the
* same as when using {@link DBRef}, the store representation is different. The reference can be anything, a single
* value, an entire {@link org.bson.Document}, basically everything that can be stored in MongoDB. By default, the
* mapping layer will use the referenced entities {@literal id} value for storage and retrieval.
*
* <pre class="code">
* public class Account {
* private String id;
* private Float total;
* }
*
* public class Person {
* private String id;
* &#64;DocumentReference
* private List&lt;Account&gt; accounts;
* }
*
* Account account = ...
*
* mongoTemplate.insert(account);
*
* template.update(Person.class)
* .matching(where("id").is(...))
* .apply(new Update().push("accounts").value(account))
* .first();
* </pre>
*
* {@link #lookup()} allows defining a query filter that is independent from the {@literal _id} field and in combination
* with {@link org.springframework.data.convert.WritingConverter writing converters} offers a flexible way of defining
* references between entities.
*
* <pre class="code">
* public class Book {
* private ObjectId id;
* private String title;
*
* &#64;Field("publisher_ac") &#64;DocumentReference(lookup = "{ 'acronym' : ?#{#target} }") private Publisher publisher;
* }
*
* public class Publisher {
*
* private ObjectId id;
* private String acronym;
* private String name;
*
* &#64;DocumentReference(lazy = true) private List&lt;Book&gt; books;
* }
*
* &#64;WritingConverter
* public class PublisherReferenceConverter implements Converter&lt;Publisher, DocumentPointer&lt;String&gt;&gt; {
*
* public DocumentPointer&lt;String&gt; convert(Publisher source) {
* return () -> source.getAcronym();
* }
* }
* </pre>
*
* @author Christoph Strobl
* @since 3.3
* @see <a href="https://docs.mongodb.com/manual/reference/database-references/#std-label-document-references">MongoDB
* Reference Documentation</a>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD })
@Reference
public @interface DocumentReference {
/**
* The database the referenced entity resides in. Uses the default database provided by
* {@link org.springframework.data.mongodb.MongoDatabaseFactory} if empty.
*
* @see MongoDatabaseFactory#getMongoDatabase()
* @see MongoDatabaseFactory#getMongoDatabase(String)
*/
String db() default "";
/**
* The collection the referenced entity resides in. Defaults to the collection of the referenced entity type.
*
* @see MongoPersistentEntity#getCollection()
*/
String collection() default "";
/**
* The single document lookup query. In case of an {@link java.util.Collection} or {@link java.util.Map} property the
* individual lookups are combined via an {@code $or} operator. {@code target} points to the source value (or
* document) stored at the reference property. Properties of {@code target} can be used to define the reference query.
*
* @return an {@literal _id} based lookup.
*/
String lookup() default "{ '_id' : ?#{#target} }";
/**
* A specific sort.
*/
String sort() default "";
/**
* Controls whether the referenced entity should be loaded lazily. This defaults to {@literal false}.
*
* @return {@literal false} by default.
*/
boolean lazy() default false;
}

View File

@@ -28,7 +28,6 @@ import org.springframework.core.annotation.AliasFor;
*
* @author Oliver Gierke
* @author Christoph Strobl
* @author Divya Srivastava
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@@ -66,34 +65,4 @@ public @interface Field {
* @since 2.2
*/
FieldType targetType() default FieldType.IMPLICIT;
/**
* Write rules when to include a property value upon conversion. If set to {@link Write#NON_NULL} (default)
* {@literal null} values are not written to the target {@code Document}. Setting the value to {@link Write#ALWAYS}
* explicitly adds an entry for the given field holding {@literal null} as a value {@code 'fieldName' : null }.
* <p />
* <strong>NOTE</strong>Setting the value to {@link Write#ALWAYS} may lead to increased document size.
*
* @return {@link Write#NON_NULL} by default.
* @since 3.3
*/
Write write() default Write.NON_NULL;
/**
* Enumeration of write strategies to define when a property is included for write conversion.
*
* @since 3.3
*/
enum Write {
/**
* Value that indicates that property is to be always included, independent of value of the property.
*/
ALWAYS,
/**
* Value that indicates that only properties with non-{@literal null} values are to be included.
*/
NON_NULL
}
}

View File

@@ -26,7 +26,6 @@ import org.springframework.data.mapping.model.FieldNamingStrategy;
import org.springframework.data.mapping.model.Property;
import org.springframework.data.mapping.model.PropertyNameFieldNamingStrategy;
import org.springframework.data.mapping.model.SimpleTypeHolder;
import org.springframework.data.util.NullableWrapperConverters;
import org.springframework.data.util.TypeInformation;
import org.springframework.lang.Nullable;
@@ -36,9 +35,8 @@ import org.springframework.lang.Nullable;
*
* @author Jon Brisbin
* @author Oliver Gierke
* @author Christoph Strobl
*/
public class MongoMappingContext extends AbstractMappingContext<MongoPersistentEntity<?>, MongoPersistentProperty>
public class MongoMappingContext extends AbstractMappingContext<BasicMongoPersistentEntity<?>, MongoPersistentProperty>
implements ApplicationContextAware {
private static final FieldNamingStrategy DEFAULT_NAMING_STRATEGY = PropertyNameFieldNamingStrategy.INSTANCE;
@@ -70,11 +68,6 @@ public class MongoMappingContext extends AbstractMappingContext<MongoPersistentE
*/
@Override
protected boolean shouldCreatePersistentEntityFor(TypeInformation<?> type) {
if (NullableWrapperConverters.supports(type.getType())) {
return false;
}
return !MongoSimpleTypes.HOLDER.isSimpleType(type.getType()) && !AbstractMap.class.isAssignableFrom(type.getType());
}
@@ -83,7 +76,7 @@ public class MongoMappingContext extends AbstractMappingContext<MongoPersistentE
* @see org.springframework.data.mapping.AbstractMappingContext#createPersistentProperty(java.lang.reflect.Field, java.beans.PropertyDescriptor, org.springframework.data.mapping.MutablePersistentEntity, org.springframework.data.mapping.SimpleTypeHolder)
*/
@Override
public MongoPersistentProperty createPersistentProperty(Property property, MongoPersistentEntity<?> owner,
public MongoPersistentProperty createPersistentProperty(Property property, BasicMongoPersistentEntity<?> owner,
SimpleTypeHolder simpleTypeHolder) {
return new CachingMongoPersistentProperty(property, owner, simpleTypeHolder, fieldNamingStrategy);
}
@@ -94,7 +87,7 @@ public class MongoMappingContext extends AbstractMappingContext<MongoPersistentE
*/
@Override
protected <T> BasicMongoPersistentEntity<T> createPersistentEntity(TypeInformation<T> typeInformation) {
return new BasicMongoPersistentEntity<>(typeInformation);
return new BasicMongoPersistentEntity<T>(typeInformation);
}
/*
@@ -103,6 +96,7 @@ public class MongoMappingContext extends AbstractMappingContext<MongoPersistentE
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
super.setApplicationContext(applicationContext);
}
@@ -132,17 +126,4 @@ public class MongoMappingContext extends AbstractMappingContext<MongoPersistentE
public void setAutoIndexCreation(boolean autoCreateIndexes) {
this.autoIndexCreation = autoCreateIndexes;
}
@Nullable
@Override
public MongoPersistentEntity<?> getPersistentEntity(MongoPersistentProperty persistentProperty) {
MongoPersistentEntity<?> entity = super.getPersistentEntity(persistentProperty);
if (entity == null || !persistentProperty.isUnwrapped()) {
return entity;
}
return new UnwrappedMongoPersistentEntity<>(entity, new UnwrapEntityContext(persistentProperty));
}
}

View File

@@ -16,7 +16,6 @@
package org.springframework.data.mongodb.core.mapping;
import org.springframework.data.mapping.PersistentEntity;
import org.springframework.data.mapping.model.MutablePersistentEntity;
import org.springframework.lang.Nullable;
/**
@@ -25,7 +24,7 @@ import org.springframework.lang.Nullable;
* @author Oliver Gierke
* @author Christoph Strobl
*/
public interface MongoPersistentEntity<T> extends MutablePersistentEntity<T, MongoPersistentProperty> {
public interface MongoPersistentEntity<T> extends PersistentEntity<T, MongoPersistentProperty> {
/**
* Returns the collection the entity shall be persisted to.
@@ -94,12 +93,4 @@ public interface MongoPersistentEntity<T> extends MutablePersistentEntity<T, Mon
return getShardKey().isSharded();
}
/**
* @return {@literal true} if the entity should be unwrapped.
* @since 3.2
*/
default boolean isUnwrapped() {
return false;
}
}

View File

@@ -28,7 +28,6 @@ import org.springframework.lang.Nullable;
* @author Patryk Wasik
* @author Thomas Darimont
* @author Christoph Strobl
* @author Divya Srivastava
*/
public interface MongoPersistentProperty extends PersistentProperty<MongoPersistentProperty> {
@@ -55,15 +54,6 @@ public interface MongoPersistentProperty extends PersistentProperty<MongoPersist
*/
int getFieldOrder();
/**
* Returns whether the property should be written to the database if its value is {@literal null}.
*
* @return
* @since 3.3
* @see Field.Write
*/
boolean writeNullValues();
/**
* Returns whether the property is a {@link com.mongodb.DBRef}. If this returns {@literal true} you can expect
* {@link #getDBRef()} to return an non-{@literal null} value.
@@ -72,15 +62,6 @@ public interface MongoPersistentProperty extends PersistentProperty<MongoPersist
*/
boolean isDbReference();
/**
* Returns whether the property is a {@link DocumentReference}. If this returns {@literal true} you can expect
* {@link #getDocumentReference()} to return an non-{@literal null} value.
*
* @return
* @since 3.3
*/
boolean isDocumentReference();
/**
* Returns whether the property is explicitly marked as an identifier property of the owning {@link PersistentEntity}.
* A property is an explicit id property if it is annotated with @see {@link Id}.
@@ -124,16 +105,6 @@ public interface MongoPersistentProperty extends PersistentProperty<MongoPersist
@Nullable
DBRef getDBRef();
/**
* Returns the {@link DocumentReference} if the property is a reference.
*
* @see #isDocumentReference()
* @return {@literal null} if not present.
* @since 3.3
*/
@Nullable
DocumentReference getDocumentReference();
/**
* Returns whether property access shall be used for reading the property value. This means it will use the getter
* instead of field access.
@@ -152,14 +123,6 @@ public interface MongoPersistentProperty extends PersistentProperty<MongoPersist
return field != null ? !FieldType.IMPLICIT.equals(field.targetType()) : false;
}
/**
* @return {@literal true} if the property should be unwrapped.
* @since 3.2
*/
default boolean isUnwrapped() {
return isEntity() && isAnnotationPresent(Unwrapped.class);
}
/**
* Simple {@link Converter} implementation to transform a {@link MongoPersistentProperty} into its field name.
*
@@ -174,10 +137,7 @@ public interface MongoPersistentProperty extends PersistentProperty<MongoPersist
* @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object)
*/
public String convert(MongoPersistentProperty source) {
if (!source.isUnwrapped()) {
return source.getFieldName();
}
return "";
return source.getFieldName();
}
}
}

View File

@@ -1,87 +0,0 @@
/*
* Copyright 2021 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.mapping;
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.core.annotation.AliasFor;
import org.springframework.data.mongodb.core.timeseries.Granularity;
/**
* Identifies a domain object to be persisted to a MongoDB Time Series collection.
*
* @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>
*/
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
@Document
public @interface TimeSeries {
/**
* The collection the document representing the entity is supposed to be stored in. If not configured, a default
* collection name will be derived from the type's name. The attribute supports SpEL expressions to dynamically
* calculate the collection based on a per operation basis.
*
* @return the name of the collection to be used.
* @see Document#collection()
*/
@AliasFor(annotation = Document.class, attribute = "collection")
String collection() default "";
/**
* Name of the property which contains the date in each time series document. <br />
* Translation of property names to {@link Field#name() annotated fieldnames} will be considered during the mapping
* process.
*
* @return never {@literal null}.
*/
String timeField();
/**
* The name of the field which contains metadata in each time series document. Should not be the {@literal id} nor
* {@link #timeField()} nor point to an {@literal array} or {@link java.util.Collection}. <br />
* Translation of property names to {@link Field#name() annotated fieldnames} will be considered during the mapping
* process.
*
* @return empty {@link String} by default.
*/
String metaField() default "";
/**
* Select the {@link Granularity granularity} parameter to define how data in the time series collection is organized.
*
* @return {@link Granularity#DEFAULT server default} by default.
*/
Granularity granularity() default Granularity.DEFAULT;
/**
* Defines the collation to apply when executing a query or creating indexes.
*
* @return an empty {@link String} by default.
* @see Document#collation()
*/
@AliasFor(annotation = Document.class, attribute = "collation")
String collation() default "";
}

View File

@@ -1,64 +0,0 @@
/*
* Copyright 2021 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.mapping;
import org.springframework.util.ObjectUtils;
/**
* @author Christoph Strobl
* @author Rogério Meneguelli Gatto
* @since 3.2
*/
class UnwrapEntityContext {
private final MongoPersistentProperty property;
public UnwrapEntityContext(MongoPersistentProperty property) {
this.property = property;
}
public MongoPersistentProperty getProperty() {
return property;
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
UnwrapEntityContext that = (UnwrapEntityContext) obj;
return ObjectUtils.nullSafeEquals(property, that.property);
}
/*
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return ObjectUtils.nullSafeHashCode(property);
}
}

View File

@@ -1,136 +0,0 @@
/*
* Copyright 2021 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.mapping;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.annotation.meta.When;
import org.springframework.core.annotation.AliasFor;
/**
* The annotation to configure a value object as flattened out in the target document.
* <p />
* Depending on the {@link OnEmpty value} of {@link #onEmpty()} the property is set to {@literal null} or an empty
* instance in the case all unwrapped values are {@literal null} when reading from the result set.
*
* @author Christoph Strobl
* @since 3.2
*/
@Documented
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD })
public @interface Unwrapped {
/**
* Set the load strategy for the unwrapped object if all contained fields yield {@literal null} values.
* <p />
* {@link Nullable @Unwrapped.Nullable} and {@link Empty @Unwrapped.Empty} offer shortcuts for this.
*
* @return never {@link} null.
*/
OnEmpty onEmpty();
/**
* @return prefix for columns in the unwrapped value object. An empty {@link String} by default.
*/
String prefix() default "";
/**
* Load strategy to be used {@link Unwrapped#onEmpty()}.
*
* @author Christoph Strobl
*/
enum OnEmpty {
USE_NULL, USE_EMPTY
}
/**
* Shortcut for a nullable unwrapped property.
*
* <pre class="code">
* &#64;Unwrapped.Nullable private Address address;
* </pre>
*
* as alternative to the more verbose
*
* <pre class="code">
* &#64;Unwrapped(onEmpty = USE_NULL) &#64;javax.annotation.Nonnull(when = When.MAYBE) private Address address;
* </pre>
*
* @author Christoph Strobl
* @see Unwrapped#onEmpty()
*/
@Unwrapped(onEmpty = OnEmpty.USE_NULL)
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.METHOD })
@javax.annotation.Nonnull(when = When.MAYBE)
@interface Nullable {
/**
* @return prefix for columns in the unwrapped value object. An empty {@link String} by default.
*/
@AliasFor(annotation = Unwrapped.class, attribute = "prefix")
String prefix() default "";
/**
* @return value for columns in the unwrapped value object. An empty {@link String} by default.
*/
@AliasFor(annotation = Unwrapped.class, attribute = "prefix")
String value() default "";
}
/**
* Shortcut for an empty unwrapped property.
*
* <pre class="code">
* &#64;Unwrapped.Empty private Address address;
* </pre>
*
* as alternative to the more verbose
*
* <pre class="code">
* &#64;Unwrapped(onEmpty = USE_EMPTY) &#64;javax.annotation.Nonnull(when = When.NEVER) private Address address;
* </pre>
*
* @author Christoph Strobl
* @see Unwrapped#onEmpty()
*/
@Unwrapped(onEmpty = OnEmpty.USE_EMPTY)
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.METHOD })
@javax.annotation.Nonnull(when = When.NEVER)
@interface Empty {
/**
* @return prefix for columns in the unwrapped value object. An empty {@link String} by default.
*/
@AliasFor(annotation = Unwrapped.class, attribute = "prefix")
String prefix() default "";
/**
* @return value for columns in the unwrapped value object. An empty {@link String} by default.
*/
@AliasFor(annotation = Unwrapped.class, attribute = "prefix")
String value() default "";
}
}

View File

@@ -1,326 +0,0 @@
/*
* Copyright 2021 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.mapping;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.springframework.data.mapping.*;
import org.springframework.data.mapping.model.PersistentPropertyAccessorFactory;
import org.springframework.data.mongodb.core.query.Collation;
import org.springframework.data.spel.EvaluationContextProvider;
import org.springframework.data.util.Streamable;
import org.springframework.data.util.TypeInformation;
import org.springframework.lang.Nullable;
/**
* Unwrapped variant of {@link MongoPersistentEntity}.
*
* @author Christoph Strobl
* @since 3.2
* @see Unwrapped
*/
class UnwrappedMongoPersistentEntity<T> implements MongoPersistentEntity<T> {
private final UnwrapEntityContext context;
private final MongoPersistentEntity<T> delegate;
public UnwrappedMongoPersistentEntity(MongoPersistentEntity<T> delegate, UnwrapEntityContext context) {
this.context = context;
this.delegate = delegate;
}
@Override
public String getCollection() {
return delegate.getCollection();
}
@Override
public String getLanguage() {
return delegate.getLanguage();
}
@Override
@Nullable
public MongoPersistentProperty getTextScoreProperty() {
return delegate.getTextScoreProperty();
}
@Override
public boolean hasTextScoreProperty() {
return delegate.hasTextScoreProperty();
}
@Override
@Nullable
public Collation getCollation() {
return delegate.getCollation();
}
@Override
public boolean hasCollation() {
return delegate.hasCollation();
}
@Override
public ShardKey getShardKey() {
return delegate.getShardKey();
}
@Override
public boolean isSharded() {
return delegate.isSharded();
}
@Override
public String getName() {
return delegate.getName();
}
@Override
@Nullable
public PreferredConstructor<T, MongoPersistentProperty> getPersistenceConstructor() {
return delegate.getPersistenceConstructor();
}
@Override
public boolean isConstructorArgument(PersistentProperty<?> property) {
return delegate.isConstructorArgument(property);
}
@Override
public boolean isIdProperty(PersistentProperty<?> property) {
return delegate.isIdProperty(property);
}
@Override
public boolean isVersionProperty(PersistentProperty<?> property) {
return delegate.isVersionProperty(property);
}
@Override
@Nullable
public MongoPersistentProperty getIdProperty() {
return delegate.getIdProperty();
}
@Override
public MongoPersistentProperty getRequiredIdProperty() {
return delegate.getRequiredIdProperty();
}
@Override
@Nullable
public MongoPersistentProperty getVersionProperty() {
return delegate.getVersionProperty();
}
@Override
public MongoPersistentProperty getRequiredVersionProperty() {
return delegate.getRequiredVersionProperty();
}
@Override
@Nullable
public MongoPersistentProperty getPersistentProperty(String name) {
return wrap(delegate.getPersistentProperty(name));
}
@Override
public MongoPersistentProperty getRequiredPersistentProperty(String name) {
MongoPersistentProperty persistentProperty = getPersistentProperty(name);
if (persistentProperty != null) {
return persistentProperty;
}
throw new IllegalStateException(String.format("Required property %s not found for %s!", name, getType()));
}
@Override
@Nullable
public MongoPersistentProperty getPersistentProperty(Class<? extends Annotation> annotationType) {
return wrap(delegate.getPersistentProperty(annotationType));
}
@Override
public Iterable<MongoPersistentProperty> getPersistentProperties(Class<? extends Annotation> annotationType) {
return Streamable.of(delegate.getPersistentProperties(annotationType)).stream().map(this::wrap)
.collect(Collectors.toList());
}
@Override
public boolean hasIdProperty() {
return delegate.hasIdProperty();
}
@Override
public boolean hasVersionProperty() {
return delegate.hasVersionProperty();
}
@Override
public Class<T> getType() {
return delegate.getType();
}
@Override
public Alias getTypeAlias() {
return delegate.getTypeAlias();
}
@Override
public TypeInformation<T> getTypeInformation() {
return delegate.getTypeInformation();
}
@Override
public void doWithProperties(PropertyHandler<MongoPersistentProperty> handler) {
delegate.doWithProperties((PropertyHandler<MongoPersistentProperty>) property -> {
handler.doWithPersistentProperty(wrap(property));
});
}
@Override
public void doWithProperties(SimplePropertyHandler handler) {
delegate.doWithProperties((SimplePropertyHandler) property -> {
if (property instanceof MongoPersistentProperty) {
handler.doWithPersistentProperty(wrap((MongoPersistentProperty) property));
} else {
handler.doWithPersistentProperty(property);
}
});
}
@Override
public void doWithAssociations(AssociationHandler<MongoPersistentProperty> handler) {
delegate.doWithAssociations(handler);
}
@Override
public void doWithAssociations(SimpleAssociationHandler handler) {
delegate.doWithAssociations(handler);
}
@Override
@Nullable
public <A extends Annotation> A findAnnotation(Class<A> annotationType) {
return delegate.findAnnotation(annotationType);
}
@Override
public <A extends Annotation> A getRequiredAnnotation(Class<A> annotationType) throws IllegalStateException {
return delegate.getRequiredAnnotation(annotationType);
}
@Override
public <A extends Annotation> boolean isAnnotationPresent(Class<A> annotationType) {
return delegate.isAnnotationPresent(annotationType);
}
@Override
public <B> PersistentPropertyAccessor<B> getPropertyAccessor(B bean) {
return delegate.getPropertyAccessor(bean);
}
@Override
public <B> PersistentPropertyPathAccessor<B> getPropertyPathAccessor(B bean) {
return delegate.getPropertyPathAccessor(bean);
}
@Override
public IdentifierAccessor getIdentifierAccessor(Object bean) {
return delegate.getIdentifierAccessor(bean);
}
@Override
public boolean isNew(Object bean) {
return delegate.isNew(bean);
}
@Override
public boolean isImmutable() {
return delegate.isImmutable();
}
@Override
public boolean requiresPropertyPopulation() {
return delegate.requiresPropertyPopulation();
}
@Override
public Iterator<MongoPersistentProperty> iterator() {
List<MongoPersistentProperty> target = new ArrayList<>();
delegate.iterator().forEachRemaining(it -> target.add(wrap(it)));
return target.iterator();
}
@Override
public void forEach(Consumer<? super MongoPersistentProperty> action) {
delegate.forEach(it -> action.accept(wrap(it)));
}
@Override
public Spliterator<MongoPersistentProperty> spliterator() {
return delegate.spliterator();
}
private MongoPersistentProperty wrap(MongoPersistentProperty source) {
if (source == null) {
return source;
}
return new UnwrappedMongoPersistentProperty(source, context);
}
@Override
public void addPersistentProperty(MongoPersistentProperty property) {
}
@Override
public void addAssociation(Association<MongoPersistentProperty> association) {
}
@Override
public void verify() throws MappingException {
}
@Override
public void setPersistentPropertyAccessorFactory(PersistentPropertyAccessorFactory factory) {
}
@Override
public void setEvaluationContextProvider(EvaluationContextProvider provider) {
}
@Override
public boolean isUnwrapped() {
return context.getProperty().isUnwrapped();
}
}

View File

@@ -1,369 +0,0 @@
/*
* Copyright 2021 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.mapping;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.springframework.data.mapping.Association;
import org.springframework.data.mapping.PersistentEntity;
import org.springframework.data.mapping.PersistentPropertyAccessor;
import org.springframework.data.util.TypeInformation;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
/**
* Unwrapped variant of {@link MongoPersistentProperty}.
*
* @author Christoph Strobl
* @author Rogério Meneguelli Gatto
* @since 3.2
* @see Unwrapped
*/
class UnwrappedMongoPersistentProperty implements MongoPersistentProperty {
private final MongoPersistentProperty delegate;
private final UnwrapEntityContext context;
public UnwrappedMongoPersistentProperty(MongoPersistentProperty delegate, UnwrapEntityContext context) {
this.delegate = delegate;
this.context = context;
}
@Override
public String getFieldName() {
if (!context.getProperty().isUnwrapped()) {
return delegate.getFieldName();
}
return context.getProperty().findAnnotation(Unwrapped.class).prefix() + delegate.getFieldName();
}
@Override
public Class<?> getFieldType() {
return delegate.getFieldType();
}
@Override
public int getFieldOrder() {
return delegate.getFieldOrder();
}
@Override
public boolean writeNullValues() {
return delegate.writeNullValues();
}
@Override
public boolean isDbReference() {
return delegate.isDbReference();
}
@Override
public boolean isDocumentReference() {
return delegate.isDocumentReference();
}
@Override
public boolean isExplicitIdProperty() {
return delegate.isExplicitIdProperty();
}
@Override
public boolean isLanguageProperty() {
return delegate.isLanguageProperty();
}
@Override
public boolean isExplicitLanguageProperty() {
return delegate.isExplicitLanguageProperty();
}
@Override
public boolean isTextScoreProperty() {
return delegate.isTextScoreProperty();
}
@Override
@Nullable
public DBRef getDBRef() {
return delegate.getDBRef();
}
@Override
@Nullable
public DocumentReference getDocumentReference() {
return delegate.getDocumentReference();
}
@Override
public boolean usePropertyAccess() {
return delegate.usePropertyAccess();
}
@Override
public boolean hasExplicitWriteTarget() {
return delegate.hasExplicitWriteTarget();
}
@Override
public PersistentEntity<?, MongoPersistentProperty> getOwner() {
return delegate.getOwner();
}
@Override
public String getName() {
return delegate.getName();
}
@Override
public Class<?> getType() {
return delegate.getType();
}
@Override
public TypeInformation<?> getTypeInformation() {
return delegate.getTypeInformation();
}
@Override
public Iterable<? extends TypeInformation<?>> getPersistentEntityTypes() {
return delegate.getPersistentEntityTypes();
}
@Override
public Iterable<? extends TypeInformation<?>> getPersistentEntityTypeInformation() {
return delegate.getPersistentEntityTypeInformation();
}
@Override
@Nullable
public Method getGetter() {
return delegate.getGetter();
}
@Override
public Method getRequiredGetter() {
return delegate.getRequiredGetter();
}
@Override
@Nullable
public Method getSetter() {
return delegate.getSetter();
}
@Override
public Method getRequiredSetter() {
return delegate.getRequiredSetter();
}
@Override
@Nullable
public Method getWither() {
return delegate.getWither();
}
@Override
public Method getRequiredWither() {
return delegate.getRequiredWither();
}
@Override
@Nullable
public Field getField() {
return delegate.getField();
}
@Override
public Field getRequiredField() {
return delegate.getRequiredField();
}
@Override
@Nullable
public String getSpelExpression() {
return delegate.getSpelExpression();
}
@Override
@Nullable
public Association<MongoPersistentProperty> getAssociation() {
return delegate.getAssociation();
}
@Override
public Association<MongoPersistentProperty> getRequiredAssociation() {
return delegate.getRequiredAssociation();
}
@Override
public boolean isEntity() {
return delegate.isEntity();
}
@Override
public boolean isIdProperty() {
return delegate.isIdProperty();
}
@Override
public boolean isVersionProperty() {
return delegate.isVersionProperty();
}
@Override
public boolean isCollectionLike() {
return delegate.isCollectionLike();
}
@Override
public boolean isMap() {
return delegate.isMap();
}
@Override
public boolean isArray() {
return delegate.isArray();
}
@Override
public boolean isTransient() {
return delegate.isTransient();
}
@Override
public boolean isWritable() {
return delegate.isWritable();
}
@Override
public boolean isImmutable() {
return delegate.isImmutable();
}
@Override
public boolean isAssociation() {
return delegate.isAssociation();
}
@Override
public boolean isUnwrapped() {
return delegate.isUnwrapped();
}
@Override
@Nullable
public Class<?> getComponentType() {
return delegate.getComponentType();
}
@Override
public Class<?> getRawType() {
return delegate.getRawType();
}
@Override
@Nullable
public Class<?> getMapValueType() {
return delegate.getMapValueType();
}
@Override
public Class<?> getActualType() {
return delegate.getActualType();
}
@Override
@Nullable
public <A extends Annotation> A findAnnotation(Class<A> annotationType) {
return delegate.findAnnotation(annotationType);
}
@Override
public <A extends Annotation> A getRequiredAnnotation(Class<A> annotationType) throws IllegalStateException {
return delegate.getRequiredAnnotation(annotationType);
}
@Override
@Nullable
public <A extends Annotation> A findPropertyOrOwnerAnnotation(Class<A> annotationType) {
return delegate.findPropertyOrOwnerAnnotation(annotationType);
}
@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) {
return delegate.isAnnotationPresent(annotationType);
}
@Override
public boolean hasActualTypeAnnotation(Class<? extends Annotation> annotationType) {
return delegate.hasActualTypeAnnotation(annotationType);
}
@Override
@Nullable
public Class<?> getAssociationTargetType() {
return delegate.getAssociationTargetType();
}
@Override
public TypeInformation<?> getAssociationTargetTypeInformation() {
return delegate.getAssociationTargetTypeInformation();
}
@Override
public <T> PersistentPropertyAccessor<T> getAccessorForOwner(T owner) {
return delegate.getAccessorForOwner(owner);
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
UnwrappedMongoPersistentProperty that = (UnwrappedMongoPersistentProperty) obj;
if (!ObjectUtils.nullSafeEquals(delegate, that.delegate)) {
return false;
}
return ObjectUtils.nullSafeEquals(context, that.context);
}
/*
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
int result = ObjectUtils.nullSafeHashCode(delegate);
result = 31 * result + ObjectUtils.nullSafeHashCode(context);
return result;
}
}

View File

@@ -77,7 +77,7 @@ public class MongoMappingEvent<T> extends ApplicationEvent {
/**
* Allows client code to change the underlying source instance by applying the given {@link Function}.
*
*
* @param mapper the {@link Function} to apply, will only be applied if the source is not {@literal null}.
* @since 2.1
*/

View File

@@ -29,7 +29,6 @@ import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.bson.BsonRegularExpression;
import org.bson.BsonType;
import org.bson.Document;
import org.bson.types.Binary;
import org.springframework.data.domain.Example;
@@ -53,7 +52,7 @@ import com.mongodb.BasicDBList;
/**
* Central class for creating queries. It follows a fluent API style so that you can easily chain together multiple
* criteria. Static import of the {@link Criteria#where Criteria.where} method improves readability.
* criteria. Static import of the 'Criteria.where' method will improve readability.
*
* @author Thomas Risberg
* @author Oliver Gierke
@@ -61,7 +60,6 @@ import com.mongodb.BasicDBList;
* @author Christoph Strobl
* @author Mark Paluch
* @author Andreas Zink
* @author Ziemowit Stolarczyk
* @author Clément Petit
*/
public class Criteria implements CriteriaDefinition {
@@ -189,42 +187,6 @@ public class Criteria implements CriteriaDefinition {
return this;
}
/**
* Creates a criterion using {@literal null} equality comparison which matches documents that either contain the item
* field whose value is {@literal null} or that do not contain the item field.
* <p />
* Use {@link #isNullValue()} to only query for documents that contain the field whose value is equal to
* {@link org.bson.BsonType#NULL}. <br />
* Use {@link #exists(boolean)} to query for documents that do (not) contain the field.
*
* @return this.
* @see <a href="https://docs.mongodb.com/manual/tutorial/query-for-null-fields/#equality-filter">Query for Null or
* Missing Fields: Equality Filter</a>
* @since 3.3
*/
public Criteria isNull() {
return is(null);
}
/**
* Creates a criterion using a {@link org.bson.BsonType} comparison which matches only documents that contain the item
* field whose value is equal to {@link org.bson.BsonType#NULL}.
* <p />
* Use {@link #isNull()} to query for documents that contain the field with a {@literal null} value or do not contain the
* field at all. <br />
* Use {@link #exists(boolean)} to query for documents that do (not) contain the field.
*
* @return this.
* @see <a href="https://docs.mongodb.com/manual/tutorial/query-for-null-fields/#type-check">Query for Null or Missing
* Fields: Type Check</a>
* @since 3.3
*/
public Criteria isNullValue() {
criteria.put("$type", BsonType.NULL.getValue());
return this;
}
private boolean lastOperatorWasNot() {
return !this.criteria.isEmpty() && "$not".equals(this.criteria.keySet().toArray()[this.criteria.size() - 1]);
}
@@ -428,22 +390,7 @@ public class Criteria implements CriteriaDefinition {
Assert.notNull(types, "Types must not be null!");
Assert.noNullElements(types, "Types must not contain null.");
return type(Arrays.asList(types));
}
/**
* Creates a criterion using the {@literal $type} operator.
*
* @param types must not be {@literal null}.
* @return this.
* @since 3.2
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/type/">MongoDB Query operator: $type</a>
*/
public Criteria type(Collection<Type> types) {
Assert.notNull(types, "Types must not be null!");
criteria.put("$type", types.stream().map(Type::value).collect(Collectors.toList()));
criteria.put("$type", Arrays.asList(types).stream().map(Type::value).collect(Collectors.toList()));
return this;
}
@@ -724,103 +671,46 @@ public class Criteria implements CriteriaDefinition {
}
/**
* Creates a criteria using the {@code $or} operator for all of the provided criteria.
* Creates an 'or' criteria using the $or operator for all of the provided criteria
* <p>
* Note that mongodb doesn't support an $or operator to be wrapped in a $not operator.
* <p>
* Note that MongoDB doesn't support an {@code $nor} operator to be wrapped in a {@code $not} operator.
*
* @throws IllegalArgumentException if this method follows a {@link #not()} call directly.
* @throws IllegalArgumentException if {@link #orOperator(Criteria...)} follows a not() call directly.
* @param criteria must not be {@literal null}.
* @return this.
*/
public Criteria orOperator(Criteria... criteria) {
Assert.notNull(criteria, "Criteria must not be null!");
return orOperator(Arrays.asList(criteria));
}
/**
* Creates a criteria using the {@code $or} operator for all of the provided criteria.
* <p>
* Note that MongoDB doesn't support an {@code $nor} operator to be wrapped in a {@code $not} operator.
*
* @throws IllegalArgumentException if this method follows a {@link #not()} call directly.
* @param criteria must not be {@literal null}.
* @return this.
* @since 3.2
*/
public Criteria orOperator(Collection<Criteria> criteria) {
Assert.notNull(criteria, "Criteria must not be null!");
BasicDBList bsonList = createCriteriaList(criteria);
return registerCriteriaChainElement(new Criteria("$or").is(bsonList));
}
/**
* Creates a criteria using the {@code $nor} operator for all of the provided criteria.
* Creates a 'nor' criteria using the $nor operator for all of the provided criteria.
* <p>
* Note that mongodb doesn't support an $nor operator to be wrapped in a $not operator.
* <p>
* Note that MongoDB doesn't support an {@code $nor} operator to be wrapped in a {@code $not} operator.
*
* @throws IllegalArgumentException if this method follows a {@link #not()} call directly.
* @throws IllegalArgumentException if {@link #norOperator(Criteria...)} follows a not() call directly.
* @param criteria must not be {@literal null}.
* @return this.
*/
public Criteria norOperator(Criteria... criteria) {
Assert.notNull(criteria, "Criteria must not be null!");
return norOperator(Arrays.asList(criteria));
}
/**
* Creates a criteria using the {@code $nor} operator for all of the provided criteria.
* <p>
* Note that MongoDB doesn't support an {@code $nor} operator to be wrapped in a {@code $not} operator.
*
* @throws IllegalArgumentException if this method follows a {@link #not()} call directly.
* @param criteria must not be {@literal null}.
* @return this.
* @since 3.2
*/
public Criteria norOperator(Collection<Criteria> criteria) {
Assert.notNull(criteria, "Criteria must not be null!");
BasicDBList bsonList = createCriteriaList(criteria);
return registerCriteriaChainElement(new Criteria("$nor").is(bsonList));
}
/**
* Creates a criteria using the {@code $and} operator for all of the provided criteria.
* Creates an 'and' criteria using the $and operator for all of the provided criteria.
* <p>
* Note that mongodb doesn't support an $and operator to be wrapped in a $not operator.
* <p>
* Note that MongoDB doesn't support an {@code $and} operator to be wrapped in a {@code $not} operator.
*
* @throws IllegalArgumentException if this method follows a {@link #not()} call directly.
* @throws IllegalArgumentException if {@link #andOperator(Criteria...)} follows a not() call directly.
* @param criteria must not be {@literal null}.
* @return this.
*/
public Criteria andOperator(Criteria... criteria) {
Assert.notNull(criteria, "Criteria must not be null!");
return andOperator(Arrays.asList(criteria));
}
/**
* Creates a criteria using the {@code $and} operator for all of the provided criteria.
* <p>
* Note that MongoDB doesn't support an {@code $and} operator to be wrapped in a {@code $not} operator.
*
* @throws IllegalArgumentException if this method follows a {@link #not()} call directly.
* @param criteria must not be {@literal null}.
* @return this.
* @since 3.2
*/
public Criteria andOperator(Collection<Criteria> criteria) {
Assert.notNull(criteria, "Criteria must not be null!");
BasicDBList bsonList = createCriteriaList(criteria);
return registerCriteriaChainElement(new Criteria("$and").is(bsonList));
}
@@ -914,7 +804,7 @@ public class Criteria implements CriteriaDefinition {
return queryCriteria;
}
private BasicDBList createCriteriaList(Collection<Criteria> criteria) {
private BasicDBList createCriteriaList(Criteria[] criteria) {
BasicDBList bsonList = new BasicDBList();
for (Criteria c : criteria) {
bsonList.add(c.getCriteriaObject());
@@ -923,13 +813,11 @@ public class Criteria implements CriteriaDefinition {
}
private void setValue(Document document, String key, Object value) {
Object existing = document.get(key);
if (existing == null) {
document.put(key, value);
} else {
throw new InvalidMongoDbApiUsageException("Due to limitations of the org.bson.Document, "
throw new InvalidMongoDbApiUsageException("Due to limitations of the com.mongodb.BasicDocument, "
+ "you can't add a second '" + key + "' expression specified as '" + key + " : " + value + "'. "
+ "Criteria already contains '" + key + " : " + existing + "'.");
}

View File

@@ -20,7 +20,7 @@ import java.util.Map;
import java.util.Map.Entry;
import org.bson.Document;
import org.springframework.data.mongodb.MongoExpression;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
@@ -37,7 +37,7 @@ import org.springframework.util.ObjectUtils;
*/
public class Field {
private final Map<String, Object> criteria = new HashMap<>();
private final Map<String, Integer> criteria = new HashMap<>();
private final Map<String, Object> slices = new HashMap<>();
private final Map<String, Criteria> elemMatchs = new HashMap<>();
private @Nullable String positionKey;
@@ -58,62 +58,6 @@ public class Field {
return this;
}
/**
* Project a given {@link MongoExpression} to a {@link FieldProjectionExpression#as(String) field} included in the
* result.
*
* <pre class="code">
*
* // { 'name' : { '$toUpper' : '$name' } }
*
* // native MongoDB expression
* .project(MongoExpression.expressionFromString("'$toUpper' : '$name'")).as("name");
*
* // Aggregation Framework expression
* .project(StringOperators.valueOf("name").toUpper()).as("name");
*
* // Aggregation Framework SpEL expression
* .project(AggregationSpELExpression.expressionOf("toUpper(name)")).as("name");
* </pre>
*
* @param expression must not be {@literal null}.
* @return new instance of {@link FieldProjectionExpression}. Define the target field name through
* {@link FieldProjectionExpression#as(String) as(String)}.
* @since 3.2
*/
public FieldProjectionExpression project(MongoExpression expression) {
return field -> Field.this.projectAs(expression, field);
}
/**
* Project a given {@link MongoExpression} to a {@link FieldProjectionExpression#as(String) field} included in the
* result.
*
* <pre class="code">
*
* // { 'name' : { '$toUpper' : '$name' } }
*
* // native MongoDB expression
* .projectAs(MongoExpression.expressionFromString("'$toUpper' : '$name'"), "name");
*
* // Aggregation Framework expression
* .projectAs(StringOperators.valueOf("name").toUpper(), "name");
*
* // Aggregation Framework SpEL expression
* .projectAs(AggregationSpELExpression.expressionOf("toUpper(name)"), "name");
* </pre>
*
* @param expression must not be {@literal null}.
* @param field the field name used in the result.
* @return new instance of {@link FieldProjectionExpression}.
* @since 3.2
*/
public Field projectAs(MongoExpression expression, String field) {
criteria.put(field, expression);
return this;
}
/**
* Include one or more {@code fields} to be returned by the query operation.
*
@@ -222,7 +166,8 @@ public class Field {
public Document getFieldsObject() {
Document document = new Document(criteria);
@SuppressWarnings({ "unchecked", "rawtypes" })
Document document = new Document((Map) criteria);
for (Entry<String, Object> entry : slices.entrySet()) {
document.put(entry.getKey(), new Document("$slice", entry.getValue()));
@@ -274,21 +219,4 @@ public class Field {
result = 31 * result + positionValue;
return result;
}
/**
* Intermediate builder part for projecting a {@link MongoExpression} to a result field.
*
* @since 3.2
* @author Christoph Strobl
*/
public interface FieldProjectionExpression {
/**
* Set the name to be used in the result and return a {@link Field}.
*
* @param name must not be {@literal null}.
* @return the calling instance {@link Field}.
*/
Field as(String name);
}
}

View File

@@ -181,11 +181,7 @@ public class Meta {
}
/**
* Enables writing to temporary files for aggregation stages and queries. When set to {@literal true}, aggregation
* stages can write data to the {@code _tmp} subdirectory in the {@code dbPath} directory.
* <p>
* Starting in MongoDB 4.2, the profiler log messages and diagnostic log messages includes a {@code usedDisk}
* indicator if any aggregation stage wrote data to temporary files due to memory restrictions.
* Set to {@literal true}, to allow aggregation stages to write data to disk.
*
* @param allowDiskUse use {@literal null} for server defaults.
* @since 3.0

View File

@@ -46,7 +46,6 @@ import org.springframework.util.Assert;
* @author Thomas Darimont
* @author Christoph Strobl
* @author Mark Paluch
* @author Anton Barkan
*/
public class Query {
@@ -373,24 +372,6 @@ public class Query {
return this;
}
/**
* Enables writing to temporary files for aggregation stages and queries. When set to {@literal true}, aggregation
* stages can write data to the {@code _tmp} subdirectory in the {@code dbPath} directory.
* <p>
* Starting in MongoDB 4.2, the profiler log messages and diagnostic log messages includes a {@code usedDisk}
* indicator if any aggregation stage wrote data to temporary files due to memory restrictions.
*
* @param allowDiskUse
* @return this.
* @see Meta#setAllowDiskUse(Boolean)
* @since 3.2
*/
public Query allowDiskUse(boolean allowDiskUse) {
meta.setAllowDiskUse(allowDiskUse);
return this;
}
/**
* Set the number of documents to return in each response batch. <br />
* Use {@literal 0 (zero)} for no limit. A <strong>negative limit</strong> closes the cursor after returning a single

View File

@@ -1,27 +0,0 @@
/*
* Copyright 2021 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.timeseries;
/**
* The Granularity of time series data that is closest to the time span between incoming measurements.
*
* @author Christoph Strobl
* @since 3.3
*/
public interface GranularityDefinition {
String name();
}

View File

@@ -18,8 +18,6 @@ package org.springframework.data.mongodb.repository.query;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.function.IntUnaryOperator;
import java.util.function.LongUnaryOperator;
import org.bson.Document;
import org.springframework.data.domain.Pageable;
@@ -44,7 +42,6 @@ import org.springframework.util.StringUtils;
*
* @author Christoph Strobl
* @author Mark Paluch
* @author Divya Srivastava
* @since 2.2
*/
abstract class AggregationUtils {
@@ -136,22 +133,6 @@ abstract class AggregationUtils {
*/
static void appendLimitAndOffsetIfPresent(List<AggregationOperation> aggregationPipeline,
ConvertingParameterAccessor accessor) {
appendLimitAndOffsetIfPresent(aggregationPipeline, accessor, LongUnaryOperator.identity(),
IntUnaryOperator.identity());
}
/**
* Append {@code $skip} and {@code $limit} aggregation stage if {@link ConvertingParameterAccessor#getSort()} is
* present.
*
* @param aggregationPipeline
* @param accessor
* @param offsetOperator
* @param limitOperator
* @since 3.3
*/
static void appendLimitAndOffsetIfPresent(List<AggregationOperation> aggregationPipeline,
ConvertingParameterAccessor accessor, LongUnaryOperator offsetOperator, IntUnaryOperator limitOperator) {
Pageable pageable = accessor.getPageable();
if (pageable.isUnpaged()) {
@@ -159,10 +140,10 @@ abstract class AggregationUtils {
}
if (pageable.getOffset() > 0) {
aggregationPipeline.add(Aggregation.skip(offsetOperator.applyAsLong(pageable.getOffset())));
aggregationPipeline.add(Aggregation.skip(pageable.getOffset()));
}
aggregationPipeline.add(Aggregation.limit(limitOperator.applyAsInt(pageable.getPageSize())));
aggregationPipeline.add(Aggregation.limit(pageable.getPageSize()));
}
/**

View File

@@ -17,13 +17,9 @@ package org.springframework.data.mongodb.repository.query;
import java.util.ArrayList;
import java.util.List;
import java.util.function.LongUnaryOperator;
import java.util.stream.Stream;
import java.util.stream.Collectors;
import org.bson.Document;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.SliceImpl;
import org.springframework.data.mapping.model.SpELExpressionEvaluator;
import org.springframework.data.mongodb.InvalidMongoDbApiUsageException;
import org.springframework.data.mongodb.core.MongoOperations;
@@ -44,12 +40,7 @@ import org.springframework.expression.ExpressionParser;
import org.springframework.util.ClassUtils;
/**
* {@link AbstractMongoQuery} implementation to run string-based aggregations using
* {@link org.springframework.data.mongodb.repository.Aggregation}.
*
* @author Christoph Strobl
* @author Divya Srivastava
* @author Mark Paluch
* @since 2.2
*/
public class StringBasedAggregation extends AbstractMongoQuery {
@@ -71,12 +62,6 @@ public class StringBasedAggregation extends AbstractMongoQuery {
ExpressionParser expressionParser, QueryMethodEvaluationContextProvider evaluationContextProvider) {
super(method, mongoOperations, expressionParser, evaluationContextProvider);
if (method.isPageQuery()) {
throw new InvalidMongoDbApiUsageException(String.format(
"Repository aggregation method '%s' does not support '%s' return type. Please use 'Slice' or 'List' instead.",
method.getName(), method.getReturnType().getType().getSimpleName()));
}
this.mongoOperations = mongoOperations;
this.mongoConverter = mongoOperations.getConverter();
this.expressionParser = expressionParser;
@@ -91,18 +76,18 @@ public class StringBasedAggregation extends AbstractMongoQuery {
protected Object doExecute(MongoQueryMethod method, ResultProcessor resultProcessor,
ConvertingParameterAccessor accessor, Class<?> typeToRead) {
if (method.isPageQuery() || method.isSliceQuery()) {
throw new InvalidMongoDbApiUsageException(String.format(
"Repository aggregation method '%s' does not support '%s' return type. Please use eg. 'List' instead.",
method.getName(), method.getReturnType().getType().getSimpleName()));
}
Class<?> sourceType = method.getDomainClass();
Class<?> targetType = typeToRead;
List<AggregationOperation> pipeline = computePipeline(method, accessor);
AggregationUtils.appendSortIfPresent(pipeline, accessor, typeToRead);
if (method.isSliceQuery()) {
AggregationUtils.appendLimitAndOffsetIfPresent(pipeline, accessor, LongUnaryOperator.identity(),
limit -> limit + 1);
} else {
AggregationUtils.appendLimitAndOffsetIfPresent(pipeline, accessor);
}
AggregationUtils.appendLimitAndOffsetIfPresent(pipeline, accessor);
boolean isSimpleReturnType = isSimpleReturnType(typeToRead);
boolean isRawAggregationResult = ClassUtils.isAssignable(AggregationResults.class, typeToRead);
@@ -110,43 +95,28 @@ public class StringBasedAggregation extends AbstractMongoQuery {
if (isSimpleReturnType) {
targetType = Document.class;
} else if (isRawAggregationResult) {
// 🙈
targetType = method.getReturnType().getRequiredActualType().getRequiredComponentType().getType();
}
AggregationOptions options = computeOptions(method, accessor);
TypedAggregation<?> aggregation = new TypedAggregation<>(sourceType, pipeline, options);
if (method.isStreamQuery()) {
Stream<?> stream = mongoOperations.aggregateStream(aggregation, targetType).stream();
if (isSimpleReturnType) {
return stream.map(it -> AggregationUtils.extractSimpleTypeResult((Document) it, typeToRead, mongoConverter));
}
return stream;
}
AggregationResults<Object> result = (AggregationResults<Object>) mongoOperations.aggregate(aggregation, targetType);
AggregationResults<?> result = mongoOperations.aggregate(aggregation, targetType);
if (isRawAggregationResult) {
return result;
}
List<Object> results = result.getMappedResults();
if (method.isCollectionQuery()) {
return isSimpleReturnType ? convertResults(typeToRead, results) : results;
}
if (method.isSliceQuery()) {
if (isSimpleReturnType) {
Pageable pageable = accessor.getPageable();
int pageSize = pageable.getPageSize();
List<Object> resultsToUse = isSimpleReturnType ? convertResults(typeToRead, results) : results;
boolean hasNext = resultsToUse.size() > pageSize;
return new SliceImpl<>(hasNext ? resultsToUse.subList(0, pageSize) : resultsToUse, pageable, hasNext);
return result.getMappedResults().stream()
.map(it -> AggregationUtils.extractSimpleTypeResult((Document) it, typeToRead, mongoConverter))
.collect(Collectors.toList());
}
return result.getMappedResults();
}
Object uniqueResult = result.getUniqueMappedResult();
@@ -156,17 +126,6 @@ public class StringBasedAggregation extends AbstractMongoQuery {
: uniqueResult;
}
private List<Object> convertResults(Class<?> typeToRead, List<Object> mappedResults) {
List<Object> list = new ArrayList<>(mappedResults.size());
for (Object it : mappedResults) {
Object extractSimpleTypeResult = AggregationUtils.extractSimpleTypeResult((Document) it, typeToRead,
mongoConverter);
list.add(extractSimpleTypeResult);
}
return list;
}
private boolean isSimpleReturnType(Class<?> targetType) {
return MongoSimpleTypes.HOLDER.isSimpleType(targetType);
}

View File

@@ -15,14 +15,12 @@
*/
package org.springframework.data.mongodb.repository.support;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
@@ -30,7 +28,6 @@ import org.springframework.data.mongodb.UncategorizedMongoDbException;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.IndexOperationsProvider;
import org.springframework.data.mongodb.core.mapping.Unwrapped;
import org.springframework.data.mongodb.core.query.Collation;
import org.springframework.data.mongodb.repository.query.MongoEntityMetadata;
import org.springframework.data.mongodb.repository.query.PartTreeMongoQuery;
@@ -39,7 +36,6 @@ import org.springframework.data.repository.query.parser.Part;
import org.springframework.data.repository.query.parser.Part.Type;
import org.springframework.data.repository.query.parser.PartTree;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import com.mongodb.MongoException;
@@ -86,14 +82,9 @@ class IndexEnsuringQueryCreationListener implements QueryCreationListener<PartTr
Sort sort = tree.getSort();
for (Part part : tree.getParts()) {
if (GEOSPATIAL_TYPES.contains(part.getType())) {
return;
}
if (isIndexOnUnwrappedType(part)) {
return;
}
String property = part.getProperty().toDotPath();
Direction order = toDirection(sort, property);
index.on(property, order);
@@ -116,7 +107,7 @@ class IndexEnsuringQueryCreationListener implements QueryCreationListener<PartTr
MongoEntityMetadata<?> metadata = query.getQueryMethod().getEntityInformation();
try {
indexOperationsProvider.indexOps(metadata.getCollectionName(), metadata.getJavaType()).ensureIndex(index);
indexOperationsProvider.indexOps(metadata.getCollectionName()).ensureIndex(index);
} catch (UncategorizedMongoDbException e) {
if (e.getCause() instanceof MongoException) {
@@ -138,19 +129,6 @@ class IndexEnsuringQueryCreationListener implements QueryCreationListener<PartTr
LOG.debug(String.format("Created %s!", index));
}
public boolean isIndexOnUnwrappedType(Part part) {
// TODO we could do it for nested fields in the
Field field = ReflectionUtils.findField(part.getProperty().getOwningType().getType(),
part.getProperty().getSegment());
if (field == null) {
return false;
}
return AnnotatedElementUtils.hasAnnotation(field, Unwrapped.class);
}
private static Direction toDirection(Sort sort, String property) {
if (sort.isUnsorted()) {

View File

@@ -39,6 +39,7 @@ import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryComposition.RepositoryFragments;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import org.springframework.data.repository.core.support.RepositoryFragment;
import org.springframework.data.repository.query.QueryLookupStrategy;
import org.springframework.data.repository.query.QueryLookupStrategy.Key;
import org.springframework.data.repository.query.QueryMethodEvaluationContextProvider;
@@ -91,21 +92,8 @@ public class MongoRepositoryFactory extends RepositoryFactorySupport {
*/
@Override
protected RepositoryFragments getRepositoryFragments(RepositoryMetadata metadata) {
return getRepositoryFragments(metadata, operations);
}
/**
* Creates {@link RepositoryFragments} based on {@link RepositoryMetadata} to add Mongo-specific extensions. Typically
* adds a {@link QuerydslMongoPredicateExecutor} if the repository interface uses Querydsl.
* <p>
* Can be overridden by subclasses to customize {@link RepositoryFragments}.
*
* @param metadata repository metadata.
* @param operations the MongoDB operations manager.
* @return
* @since 3.2.1
*/
protected RepositoryFragments getRepositoryFragments(RepositoryMetadata metadata, MongoOperations operations) {
RepositoryFragments fragments = RepositoryFragments.empty();
boolean isQueryDslRepository = QUERY_DSL_PRESENT
&& QuerydslPredicateExecutor.class.isAssignableFrom(metadata.getRepositoryInterface());
@@ -117,11 +105,14 @@ public class MongoRepositoryFactory extends RepositoryFactorySupport {
"Cannot combine Querydsl and reactive repository support in a single interface");
}
return RepositoryFragments
.just(new QuerydslMongoPredicateExecutor<>(getEntityInformation(metadata.getDomainType()), operations));
MongoEntityInformation<?, Serializable> entityInformation = getEntityInformation(metadata.getDomainType(),
metadata);
fragments = fragments.append(RepositoryFragment.implemented(
getTargetRepositoryViaReflection(QuerydslMongoPredicateExecutor.class, entityInformation, operations)));
}
return RepositoryFragments.empty();
return fragments;
}
/*

View File

@@ -90,7 +90,7 @@ public class MongoRepositoryFactoryBean<T extends Repository<S, ID>, S, ID exten
if (createIndexesForQueryMethods) {
factory.addQueryCreationListener(
new IndexEnsuringQueryCreationListener((collectionName, javaType) -> operations.indexOps(javaType)));
new IndexEnsuringQueryCreationListener(collectionName -> operations.indexOps(collectionName)));
}
return factory;

View File

@@ -0,0 +1,459 @@
/*
* Copyright 2018-2021 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.repository.support;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.regex.Pattern;
import org.bson.BsonJavaScript;
import org.bson.BsonRegularExpression;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import com.mongodb.DBRef;
import com.querydsl.core.types.*;
import com.querydsl.mongodb.MongodbOps;
/**
* <p>
* Serializes the given Querydsl query to a Document query for MongoDB.
* </p>
* <p>
* Original implementation source {@link com.querydsl.mongodb.MongodbSerializer} by {@literal The Querydsl Team}
* (<a href="http://www.querydsl.com/team">http://www.querydsl.com/team</a>) licensed under the Apache License, Version
* 2.0.
* </p>
* Modified to use {@link Document} instead of {@link com.mongodb.DBObject}, updated nullable types and code format. Use
* Bson specific types and add {@link QuerydslMongoOps#NO_MATCH}.
*
* @author laimw
* @author Mark Paluch
* @author Christoph Strobl
* @author Mikhail Kaduchka
* @author Enrique Leon Molina
* @since 2.1
*/
abstract class MongodbDocumentSerializer implements Visitor<Object, Void> {
@Nullable
Object handle(Expression<?> expression) {
return expression.accept(this, null);
}
/**
* Create the MongoDB specific query document.
*
* @param predicate must not be {@literal null}.
* @return empty {@link Document} by default.
*/
Document toQuery(Predicate predicate) {
Object value = handle(predicate);
if (value == null) {
return new Document();
}
Assert.isInstanceOf(Document.class, value,
() -> String.format("Invalid type. Expected Document but found %s", value.getClass()));
return (Document) value;
}
/**
* Create the MongoDB specific sort document.
*
* @param orderBys must not be {@literal null}.
* @return empty {@link Document} by default.
*/
Document toSort(List<OrderSpecifier<?>> orderBys) {
Document sort = new Document();
orderBys.forEach(orderSpecifier -> {
Object key = orderSpecifier.getTarget().accept(this, null);
Assert.notNull(key, () -> String.format("Mapped sort key for %s must not be null!", orderSpecifier));
sort.append(key.toString(), orderSpecifier.getOrder() == Order.ASC ? 1 : -1);
});
return sort;
}
/*
* (non-Javadoc)
* @see com.querydsl.core.types.Visitor#visit(com.querydsl.core.types.Constant, java.lang.Void)
*/
@Override
public Object visit(Constant<?> expr, Void context) {
if (!Enum.class.isAssignableFrom(expr.getType())) {
return expr.getConstant();
}
@SuppressWarnings("unchecked") // Guarded by previous check
Constant<? extends Enum<?>> expectedExpr = (Constant<? extends Enum<?>>) expr;
return expectedExpr.getConstant().name();
}
/*
* (non-Javadoc)
* @see com.querydsl.core.types.Visitor#visit(com.querydsl.core.types.TemplateExpression, java.lang.Void)
*/
@Override
public Object visit(TemplateExpression<?> expr, Void context) {
throw new UnsupportedOperationException();
}
/*
* (non-Javadoc)
* @see com.querydsl.core.types.Visitor#visit(com.querydsl.core.types.FactoryExpression, java.lang.Void)
*/
@Override
public Object visit(FactoryExpression<?> expr, Void context) {
throw new UnsupportedOperationException();
}
protected String asDBKey(Operation<?> expr, int index) {
String key = (String) asDBValue(expr, index);
Assert.hasText(key, () -> String.format("Mapped key must not be null nor empty for expression %s.", expr));
return key;
}
@Nullable
protected Object asDBValue(Operation<?> expr, int index) {
return expr.getArg(index).accept(this, null);
}
private String regexValue(Operation<?> expr, int index) {
Object value = expr.getArg(index).accept(this, null);
Assert.notNull(value, () -> String.format("Regex for %s must not be null.", expr));
return Pattern.quote(value.toString());
}
protected Document asDocument(String key, @Nullable Object value) {
return new Document(key, value);
}
@SuppressWarnings("unchecked")
@Override
public Object visit(Operation<?> expr, Void context) {
Operator op = expr.getOperator();
if (op == Ops.EQ) {
if (expr.getArg(0) instanceof Operation) {
Operation<?> lhs = (Operation<?>) expr.getArg(0);
if (lhs.getOperator() == Ops.COL_SIZE || lhs.getOperator() == Ops.ARRAY_SIZE) {
return asDocument(asDBKey(lhs, 0), asDocument("$size", asDBValue(expr, 1)));
} else {
throw new UnsupportedOperationException("Illegal operation " + expr);
}
} else if (expr.getArg(0) instanceof Path) {
Path<?> path = (Path<?>) expr.getArg(0);
Constant<?> constant = (Constant<?>) expr.getArg(1);
return asDocument(asDBKey(expr, 0), convert(path, constant));
}
} else if (op == Ops.STRING_IS_EMPTY) {
return asDocument(asDBKey(expr, 0), "");
} else if (op == Ops.AND) {
Queue<Map<Object, Object>> pendingDocuments = collectConnectorArgs("$and", expr);
List<Map<Object, Object>> unmergeableDocuments = new ArrayList<>();
List<Map<Object, Object>> generatedDocuments = new ArrayList<>();
while (!pendingDocuments.isEmpty()) {
Map<Object, Object> lhs = pendingDocuments.poll();
for (Map<Object, Object> rhs : pendingDocuments) {
Set<Object> lhs2 = new LinkedHashSet<>(lhs.keySet());
lhs2.retainAll(rhs.keySet());
if (lhs2.isEmpty()) {
lhs.putAll(rhs);
} else {
unmergeableDocuments.add(rhs);
}
}
generatedDocuments.add(lhs);
pendingDocuments = new LinkedList<>(unmergeableDocuments);
unmergeableDocuments = new LinkedList<>();
}
return generatedDocuments.size() == 1 ? generatedDocuments.get(0) : asDocument("$and", generatedDocuments);
} else if (op == Ops.NOT) {
// Handle the not's child
Operation<?> subOperation = (Operation<?>) expr.getArg(0);
Operator subOp = subOperation.getOperator();
if (subOp == Ops.IN) {
return visit(
ExpressionUtils.operation(Boolean.class, Ops.NOT_IN, subOperation.getArg(0), subOperation.getArg(1)),
context);
} else {
Document arg = (Document) handle(expr.getArg(0));
return negate(arg);
}
} else if (op == Ops.OR) {
return asDocument("$or", collectConnectorArgs("$or", expr));
} else if (op == Ops.NE) {
Path<?> path = (Path<?>) expr.getArg(0);
Constant<?> constant = (Constant<?>) expr.getArg(1);
return asDocument(asDBKey(expr, 0), asDocument("$ne", convert(path, constant)));
} else if (op == Ops.STARTS_WITH) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression("^" + regexValue(expr, 1)));
} else if (op == Ops.STARTS_WITH_IC) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression("^" + regexValue(expr, 1), "i"));
} else if (op == Ops.ENDS_WITH) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression(regexValue(expr, 1) + "$"));
} else if (op == Ops.ENDS_WITH_IC) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression(regexValue(expr, 1) + "$", "i"));
} else if (op == Ops.EQ_IGNORE_CASE) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression("^" + regexValue(expr, 1) + "$", "i"));
} else if (op == Ops.STRING_CONTAINS) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression(".*" + regexValue(expr, 1) + ".*"));
} else if (op == Ops.STRING_CONTAINS_IC) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression(".*" + regexValue(expr, 1) + ".*", "i"));
} else if (op == Ops.MATCHES) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression(asDBValue(expr, 1).toString()));
} else if (op == Ops.MATCHES_IC) {
return asDocument(asDBKey(expr, 0), new BsonRegularExpression(asDBValue(expr, 1).toString(), "i"));
} else if (op == Ops.LIKE) {
String regex = ExpressionUtils.likeToRegex((Expression) expr.getArg(1)).toString();
return asDocument(asDBKey(expr, 0), new BsonRegularExpression(regex));
} else if (op == Ops.BETWEEN) {
Document value = new Document("$gte", asDBValue(expr, 1));
value.append("$lte", asDBValue(expr, 2));
return asDocument(asDBKey(expr, 0), value);
} else if (op == Ops.IN) {
int constIndex = 0;
int exprIndex = 1;
if (expr.getArg(1) instanceof Constant<?>) {
constIndex = 1;
exprIndex = 0;
}
if (Collection.class.isAssignableFrom(expr.getArg(constIndex).getType())) {
@SuppressWarnings("unchecked") // guarded by previous check
Collection<?> values = ((Constant<? extends Collection<?>>) expr.getArg(constIndex)).getConstant();
return asDocument(asDBKey(expr, exprIndex), asDocument("$in", values));
} else {
Path<?> path = (Path<?>) expr.getArg(exprIndex);
Constant<?> constant = (Constant<?>) expr.getArg(constIndex);
return asDocument(asDBKey(expr, exprIndex), convert(path, constant));
}
} else if (op == Ops.NOT_IN) {
int constIndex = 0;
int exprIndex = 1;
if (expr.getArg(1) instanceof Constant<?>) {
constIndex = 1;
exprIndex = 0;
}
if (Collection.class.isAssignableFrom(expr.getArg(constIndex).getType())) {
@SuppressWarnings("unchecked") // guarded by previous check
Collection<?> values = ((Constant<? extends Collection<?>>) expr.getArg(constIndex)).getConstant();
return asDocument(asDBKey(expr, exprIndex), asDocument("$nin", values));
} else {
Path<?> path = (Path<?>) expr.getArg(exprIndex);
Constant<?> constant = (Constant<?>) expr.getArg(constIndex);
return asDocument(asDBKey(expr, exprIndex), asDocument("$ne", convert(path, constant)));
}
} else if (op == Ops.COL_IS_EMPTY) {
List<Object> list = new ArrayList<>(2);
list.add(asDocument(asDBKey(expr, 0), new ArrayList<Object>()));
list.add(asDocument(asDBKey(expr, 0), asDocument("$exists", false)));
return asDocument("$or", list);
} else if (op == Ops.LT) {
return asDocument(asDBKey(expr, 0), asDocument("$lt", asDBValue(expr, 1)));
} else if (op == Ops.GT) {
return asDocument(asDBKey(expr, 0), asDocument("$gt", asDBValue(expr, 1)));
} else if (op == Ops.LOE) {
return asDocument(asDBKey(expr, 0), asDocument("$lte", asDBValue(expr, 1)));
} else if (op == Ops.GOE) {
return asDocument(asDBKey(expr, 0), asDocument("$gte", asDBValue(expr, 1)));
} else if (op == Ops.IS_NULL) {
return asDocument(asDBKey(expr, 0), asDocument("$exists", false));
} else if (op == Ops.IS_NOT_NULL) {
return asDocument(asDBKey(expr, 0), asDocument("$exists", true));
} else if (op == Ops.CONTAINS_KEY) {
Path<?> path = (Path<?>) expr.getArg(0);
Expression<?> key = expr.getArg(1);
return asDocument(visit(path, context) + "." + key.toString(), asDocument("$exists", true));
} else if (op == MongodbOps.NEAR) {
return asDocument(asDBKey(expr, 0), asDocument("$near", asDBValue(expr, 1)));
} else if (op == MongodbOps.NEAR_SPHERE) {
return asDocument(asDBKey(expr, 0), asDocument("$nearSphere", asDBValue(expr, 1)));
} else if (op == MongodbOps.ELEM_MATCH) {
return asDocument(asDBKey(expr, 0), asDocument("$elemMatch", asDBValue(expr, 1)));
} else if (op == QuerydslMongoOps.NO_MATCH) {
return new Document("$where", new BsonJavaScript("function() { return false }"));
}
throw new UnsupportedOperationException("Illegal operation " + expr);
}
private Object negate(Document arg) {
List<Object> list = new ArrayList<>();
for (Map.Entry<String, Object> entry : arg.entrySet()) {
if (entry.getKey().equals("$or")) {
list.add(asDocument("$nor", entry.getValue()));
} else if (entry.getKey().equals("$and")) {
List<Object> list2 = new ArrayList<>();
for (Object o : ((Collection) entry.getValue())) {
list2.add(negate((Document) o));
}
list.add(asDocument("$or", list2));
} else if (entry.getValue() instanceof Pattern || entry.getValue() instanceof BsonRegularExpression) {
list.add(asDocument(entry.getKey(), asDocument("$not", entry.getValue())));
} else if (entry.getValue() instanceof Document) {
list.add(negate(entry.getKey(), (Document) entry.getValue()));
} else {
list.add(asDocument(entry.getKey(), asDocument("$ne", entry.getValue())));
}
}
return list.size() == 1 ? list.get(0) : asDocument("$or", list);
}
private Object negate(String key, Document value) {
if (value.size() == 1) {
return asDocument(key, asDocument("$not", value));
} else {
List<Object> list2 = new ArrayList<>();
for (Map.Entry<String, Object> entry2 : value.entrySet()) {
list2.add(asDocument(key, asDocument("$not", asDocument(entry2.getKey(), entry2.getValue()))));
}
return asDocument("$or", list2);
}
}
protected Object convert(Path<?> property, Constant<?> constant) {
if (isReference(property)) {
return asReference(constant.getConstant());
} else if (isId(property)) {
if (isReference(property.getMetadata().getParent())) {
return asReferenceKey(property.getMetadata().getParent().getType(), constant.getConstant());
} else if (constant.getType().equals(String.class) && isImplicitObjectIdConversion()) {
String id = (String) constant.getConstant();
return ObjectId.isValid(id) ? new ObjectId(id) : id;
}
}
return visit(constant, null);
}
protected boolean isImplicitObjectIdConversion() {
return true;
}
protected DBRef asReferenceKey(Class<?> entity, Object id) {
// TODO override in subclass
throw new UnsupportedOperationException();
}
protected abstract DBRef asReference(Object constant);
protected abstract boolean isReference(@Nullable Path<?> arg);
protected boolean isId(Path<?> arg) {
// TODO override in subclass
return false;
}
@Override
public String visit(Path<?> expr, Void context) {
PathMetadata metadata = expr.getMetadata();
if (metadata.getParent() != null) {
Path<?> parent = metadata.getParent();
if (parent.getMetadata().getPathType() == PathType.DELEGATE) {
parent = parent.getMetadata().getParent();
}
if (metadata.getPathType() == PathType.COLLECTION_ANY) {
return visit(parent, context);
} else if (parent.getMetadata().getPathType() != PathType.VARIABLE) {
String rv = getKeyForPath(expr, metadata);
String parentStr = visit(parent, context);
return rv != null ? parentStr + "." + rv : parentStr;
}
}
return getKeyForPath(expr, metadata);
}
protected String getKeyForPath(Path<?> expr, PathMetadata metadata) {
return metadata.getElement().toString();
}
@Override
public Object visit(SubQueryExpression<?> expr, Void context) {
throw new UnsupportedOperationException();
}
@Override
public Object visit(ParamExpression<?> expr, Void context) {
throw new UnsupportedOperationException();
}
private LinkedList<Map<Object, Object>> collectConnectorArgs(String operator, Operation<?> operation) {
LinkedList<Map<Object, Object>> pendingDocuments = new LinkedList<>();
for (Expression<?> exp : operation.getArgs()) {
Map<Object, Object> document = (Map<Object, Object>) handle(exp);
if (document.keySet().size() == 1 && document.containsKey(operator)) {
pendingDocuments.addAll((Collection<Map<Object, Object>>) document.get(operator));
} else {
pendingDocuments.add(document);
}
}
return pendingDocuments;
}
}

View File

@@ -34,8 +34,6 @@ import com.querydsl.core.types.FactoryExpression;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.ParamExpression;
import com.querydsl.core.types.Predicate;
import com.querydsl.mongodb.document.AbstractMongodbQuery;
import com.querydsl.mongodb.document.MongodbDocumentSerializer;
/**
* {@code QuerydslAbstractMongodbQuery} provides a base class for general Querydsl query implementation.
@@ -51,12 +49,8 @@ import com.querydsl.mongodb.document.MongodbDocumentSerializer;
* @author Mark Paluch
* @author Christoph Strobl
* @since 2.1
* @deprecated since 3.3, use Querydsl's {@link AbstractMongodbQuery} directly. This class is deprecated for removal
* with the next major release.
*/
@Deprecated
public abstract class QuerydslAbstractMongodbQuery<K, Q extends QuerydslAbstractMongodbQuery<K, Q>>
extends AbstractMongodbQuery<Q>
implements SimpleQuery<Q> {
private static final JsonWriterSettings JSON_WRITER_SETTINGS = JsonWriterSettings.builder().outputMode(JsonMode.SHELL)
@@ -73,8 +67,6 @@ public abstract class QuerydslAbstractMongodbQuery<K, Q extends QuerydslAbstract
@SuppressWarnings("unchecked")
QuerydslAbstractMongodbQuery(MongodbDocumentSerializer serializer) {
super(serializer);
this.queryMixin = new QueryMixin<>((Q) this, new DefaultQueryMetadata(), false);
this.serializer = serializer;
}
@@ -166,6 +158,22 @@ public abstract class QuerydslAbstractMongodbQuery<K, Q extends QuerydslAbstract
return projection;
}
/**
* Compute the filer {@link Document} from the given {@link Predicate}.
*
* @param predicate can be {@literal null}.
* @return an empty {@link Document} if predicate is {@literal null}.
* @see MongodbDocumentSerializer#toQuery(Predicate)
*/
protected Document createQuery(@Nullable Predicate predicate) {
if (predicate == null) {
return new Document();
}
return serializer.toQuery(predicate);
}
/**
* Compute the sort {@link Document} from the given list of {@link OrderSpecifier order specifiers}.
*
@@ -177,6 +185,24 @@ public abstract class QuerydslAbstractMongodbQuery<K, Q extends QuerydslAbstract
return serializer.toSort(orderSpecifiers);
}
/**
* Get the actual {@link QueryMixin} delegate.
*
* @return
*/
QueryMixin<Q> getQueryMixin() {
return queryMixin;
}
/**
* Get the where definition as a Document instance
*
* @return
*/
Document asDocument() {
return createQuery(queryMixin.getMetadata().getWhere());
}
/**
* Returns the {@literal Mongo Shell} representation of the query. <br />
* The following query

View File

@@ -37,10 +37,7 @@ import com.querydsl.mongodb.MongodbOps;
* @author Mark Paluch
* @author Christoph Strobl
* @since 2.1
* @deprecated since 3.3, use Querydsl's {@link com.querydsl.mongodb.document.AnyEmbeddedBuilder} directly. This class
* is deprecated for removal with the next major release.
*/
@Deprecated
public class QuerydslAnyEmbeddedBuilder<Q extends QuerydslAbstractMongodbQuery<K, Q>, K> {
private final QueryMixin<Q> queryMixin;

View File

@@ -0,0 +1,272 @@
/*
* Copyright 2018-2021 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.repository.support;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.springframework.data.mongodb.core.ExecutableFindOperation.FindWithProjection;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.lang.Nullable;
import org.springframework.util.LinkedMultiValueMap;
import com.mysema.commons.lang.CloseableIterator;
import com.querydsl.core.Fetchable;
import com.querydsl.core.JoinExpression;
import com.querydsl.core.QueryMetadata;
import com.querydsl.core.QueryModifiers;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Operation;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.CollectionPathBase;
/**
* {@link Fetchable} MongoDB query with utilizing {@link MongoOperations} for command execution.
*
* @param <K> result type
* @param <Q> concrete subtype
* @author Mark Paluch
* @author Christoph Strobl
* @since 2.1
*/
abstract class QuerydslFetchableMongodbQuery<K, Q extends QuerydslFetchableMongodbQuery<K, Q>>
extends QuerydslAbstractMongodbQuery<K, Q> implements Fetchable<K> {
private final Class<K> entityClass;
private final String collection;
private final MongoOperations mongoOperations;
private final FindWithProjection<K> find;
QuerydslFetchableMongodbQuery(MongodbDocumentSerializer serializer, Class<? extends K> entityClass, String collection,
MongoOperations mongoOperations) {
super(serializer);
this.entityClass = (Class<K>) entityClass;
this.collection = collection;
this.mongoOperations = mongoOperations;
find = mongoOperations.query(this.entityClass).inCollection(collection);
}
/*
* (non-Javadoc)
* @see com.querydsl.core.Fetchable#iterable()
*/
@Override
public CloseableIterator<K> iterate() {
org.springframework.data.util.CloseableIterator<? extends K> stream = mongoOperations.stream(createQuery(),
entityClass, collection);
return new CloseableIterator<K>() {
@Override
public boolean hasNext() {
return stream.hasNext();
}
@Override
public K next() {
return stream.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("Cannot remove from iterator while streaming data.");
}
@Override
public void close() {
stream.close();
}
};
}
/*
* (non-Javadoc)
* @see com.querydsl.core.Fetchable#fetch()
*/
@Override
public List<K> fetch() {
return find.matching(createQuery()).all();
}
/*
* (non-Javadoc)
* @see com.querydsl.core.Fetchable#fetchFirst()
*/
@Override
public K fetchFirst() {
return find.matching(createQuery()).firstValue();
}
/*
* (non-Javadoc)
* @see com.querydsl.core.Fetchable#fetchOne()
*/
@Override
public K fetchOne() {
return find.matching(createQuery()).oneValue();
}
/*
* (non-Javadoc)
* @see com.querydsl.core.Fetchable#fetchResults()
*/
@Override
public QueryResults<K> fetchResults() {
long total = fetchCount();
return total > 0L ? new QueryResults<>(fetch(), getQueryMixin().getMetadata().getModifiers(), total)
: QueryResults.emptyResults();
}
/*
* (non-Javadoc)
* @see com.querydsl.core.Fetchable#fetchCount()
*/
@Override
public long fetchCount() {
return find.matching(Query.of(createQuery()).skip(-1).limit(-1)).count();
}
/**
* Define a join.
*
* @param ref reference
* @param target join target
* @return new instance of {@link QuerydslJoinBuilder}.
*/
public <T> QuerydslJoinBuilder<Q, K, T> join(Path<T> ref, Path<T> target) {
return new QuerydslJoinBuilder<>(getQueryMixin(), ref, target);
}
/**
* Define a join.
*
* @param ref reference
* @param target join target
* @return new instance of {@link QuerydslJoinBuilder}.
*/
public <T> QuerydslJoinBuilder<Q, K, T> join(CollectionPathBase<?, T, ?> ref, Path<T> target) {
return new QuerydslJoinBuilder<>(getQueryMixin(), ref, target);
}
/**
* Define a constraint for an embedded object.
*
* @param collection collection must not be {@literal null}.
* @param target target must not be {@literal null}.
* @return new instance of {@link QuerydslAnyEmbeddedBuilder}.
*/
public <T> QuerydslAnyEmbeddedBuilder<Q, K> anyEmbedded(Path<? extends Collection<T>> collection, Path<T> target) {
return new QuerydslAnyEmbeddedBuilder<>(getQueryMixin(), collection);
}
protected org.springframework.data.mongodb.core.query.Query createQuery() {
QueryMetadata metadata = getQueryMixin().getMetadata();
return createQuery(createFilter(metadata), metadata.getProjection(), metadata.getModifiers(),
metadata.getOrderBy());
}
protected org.springframework.data.mongodb.core.query.Query createQuery(@Nullable Predicate filter,
@Nullable Expression<?> projection, QueryModifiers modifiers, List<OrderSpecifier<?>> orderBy) {
BasicQuery basicQuery = new BasicQuery(createQuery(filter), createProjection(projection));
Integer limit = modifiers.getLimitAsInteger();
Integer offset = modifiers.getOffsetAsInteger();
if (limit != null) {
basicQuery.limit(limit);
}
if (offset != null) {
basicQuery.skip(offset);
}
if (orderBy.size() > 0) {
basicQuery.setSortObject(createSort(orderBy));
}
return basicQuery;
}
@Nullable
protected Predicate createFilter(QueryMetadata metadata) {
Predicate filter;
if (!metadata.getJoins().isEmpty()) {
filter = ExpressionUtils.allOf(metadata.getWhere(), createJoinFilter(metadata));
} else {
filter = metadata.getWhere();
}
return filter;
}
@SuppressWarnings("unchecked")
@Nullable
protected Predicate createJoinFilter(QueryMetadata metadata) {
LinkedMultiValueMap<Expression<?>, Predicate> predicates = new LinkedMultiValueMap<>();
List<JoinExpression> joins = metadata.getJoins();
for (int i = joins.size() - 1; i >= 0; i--) {
JoinExpression join = joins.get(i);
Path<?> source = (Path) ((Operation<?>) join.getTarget()).getArg(0);
Path<?> target = (Path) ((Operation<?>) join.getTarget()).getArg(1);
Collection<Predicate> extraFilters = predicates.get(target.getRoot());
Predicate filter = ExpressionUtils.allOf(join.getCondition(), allOf(extraFilters));
List<? extends Object> ids = getIds(target.getType(), filter);
if (ids.isEmpty()) {
return ExpressionUtils.predicate(QuerydslMongoOps.NO_MATCH, source);
}
Path<?> path = ExpressionUtils.path(String.class, source, "$id");
predicates.add(source.getRoot(), ExpressionUtils.in((Path<Object>) path, ids));
}
Path<?> source = (Path) ((Operation) joins.get(0).getTarget()).getArg(0);
return allOf(predicates.get(source.getRoot()));
}
private Predicate allOf(Collection<Predicate> predicates) {
return predicates != null ? ExpressionUtils.allOf(predicates) : null;
}
/**
* Fetch the list of ids matching a given condition.
*
* @param targetType must not be {@literal null}.
* @param condition must not be {@literal null}.
* @return empty {@link List} if none found.
*/
protected List<Object> getIds(Class<?> targetType, Predicate condition) {
Query query = createQuery(condition, null, QueryModifiers.EMPTY, Collections.emptyList());
return mongoOperations.findDistinct(query, "_id", targetType, Object.class);
}
}

View File

@@ -0,0 +1,67 @@
/*
* Copyright 2018-2021 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.repository.support;
import com.querydsl.core.JoinType;
import com.querydsl.core.support.QueryMixin;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.Predicate;
/**
* {@code QuerydslJoinBuilder} is a builder for join constraints.
* <p>
* Original implementation source {@link com.querydsl.mongodb.JoinBuilder} by {@literal The Querydsl Team}
* (<a href="http://www.querydsl.com/team">http://www.querydsl.com/team</a>) licensed under the Apache License, Version
* 2.0.
* </p>
* Modified for usage with {@link QuerydslAbstractMongodbQuery}.
*
* @param <Q>
* @param <T>
* @author tiwe
* @author Mark Paluch
* @author Christoph Strobl
* @since 2.1
*/
public class QuerydslJoinBuilder<Q extends QuerydslAbstractMongodbQuery<K, Q>, K, T> {
private final QueryMixin<Q> queryMixin;
private final Path<?> ref;
private final Path<T> target;
QuerydslJoinBuilder(QueryMixin<Q> queryMixin, Path<?> ref, Path<T> target) {
this.queryMixin = queryMixin;
this.ref = ref;
this.target = target;
}
/**
* Add the given join conditions.
*
* @param conditions must not be {@literal null}.
* @return the target {@link QueryMixin}.
* @see QueryMixin#on(Predicate)
*/
@SuppressWarnings("unchecked")
public Q on(Predicate... conditions) {
queryMixin.addJoin(JoinType.JOIN, ExpressionUtils.as((Path) ref, target));
queryMixin.on(conditions);
return queryMixin.getSelf();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2021 the original author or authors.
* Copyright 2018-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,33 +13,31 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.timeseries;
package org.springframework.data.mongodb.repository.support;
import com.querydsl.core.types.Operator;
/**
* {@link GranularityDefinition Granularities} available for Time Series data.
* Spring Data specific {@link Operator operators} for usage with Querydsl and MongoDB.
*
* @author Christoph Strobl
* @since 3.3
* @since 2.1
*/
public enum Granularity implements GranularityDefinition {
enum QuerydslMongoOps implements Operator {
/**
* Server default value to indicate no explicit value should be sent.
* {@link Operator} always evaluating to {@literal false}.
*/
DEFAULT,
NO_MATCH(Boolean.class);
/**
* High frequency ingestion.
*/
SECONDS,
private final Class<?> type;
/**
* Medium frequency ingestion.
*/
MINUTES,
QuerydslMongoOps(Class<?> type) {
this.type = type;
}
/**
* Low frequency ingestion.
*/
HOURS
@Override
public Class<?> getType() {
return type;
}
}

View File

@@ -27,7 +27,7 @@ import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.querydsl.EntityPathResolver;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.querydsl.SimpleEntityPathResolver;
import org.springframework.data.support.PageableExecutionUtils;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.util.Assert;
import com.querydsl.core.NonUniqueResultException;

View File

@@ -97,7 +97,7 @@ public class ReactiveMongoRepositoryFactoryBean<T extends Repository<S, ID>, S,
if (createIndexesForQueryMethods) {
factory.addQueryCreationListener(new IndexEnsuringQueryCreationListener(
(collectionName, javaType) -> IndexOperationsAdapter.blocking(operations.indexOps(javaType))));
collectionName -> IndexOperationsAdapter.blocking(operations.indexOps(collectionName))));
}
return factory;

View File

@@ -22,9 +22,6 @@ import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.ReactiveFindOperation.FindWithProjection;
import org.springframework.data.mongodb.core.ReactiveMongoOperations;
import org.springframework.data.mongodb.core.query.BasicQuery;
@@ -43,21 +40,19 @@ import com.querydsl.core.types.Operation;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.Predicate;
import com.querydsl.mongodb.MongodbOps;
import com.querydsl.mongodb.document.MongodbDocumentSerializer;
import com.querydsl.core.types.dsl.CollectionPathBase;
/**
* MongoDB query with utilizing {@link ReactiveMongoOperations} for command execution.
*
* @implNote This class uses {@link MongoOperations} to directly convert documents into the target entity type. Also, we
* want entites to participate in lifecycle events and entity callbacks.
* @param <K> result type
* @author Mark Paluch
* @author Christoph Strobl
* @since 2.2
*/
class ReactiveSpringDataMongodbQuery<K> extends SpringDataMongodbQuerySupport<ReactiveSpringDataMongodbQuery<K>> {
class ReactiveSpringDataMongodbQuery<K> extends QuerydslAbstractMongodbQuery<K, ReactiveSpringDataMongodbQuery<K>> {
private final Class<K> entityClass;
private final ReactiveMongoOperations mongoOperations;
private final FindWithProjection<K> find;
@@ -65,15 +60,15 @@ class ReactiveSpringDataMongodbQuery<K> extends SpringDataMongodbQuerySupport<Re
this(new SpringDataMongodbSerializer(mongoOperations.getConverter()), mongoOperations, entityClass, null);
}
@SuppressWarnings("unchecked")
ReactiveSpringDataMongodbQuery(MongodbDocumentSerializer serializer, ReactiveMongoOperations mongoOperations,
Class<? extends K> entityClass, @Nullable String collection) {
super(serializer);
this.entityClass = (Class<K>) entityClass;
this.mongoOperations = mongoOperations;
this.find = StringUtils.hasText(collection) ? mongoOperations.query((Class<K>) entityClass).inCollection(collection)
: mongoOperations.query((Class<K>) entityClass);
this.find = StringUtils.hasText(collection) ? mongoOperations.query(this.entityClass).inCollection(collection)
: mongoOperations.query(this.entityClass);
}
/**
@@ -104,11 +99,48 @@ class ReactiveSpringDataMongodbQuery<K> extends SpringDataMongodbQuerySupport<Re
return createQuery().flatMap(it -> find.matching(it).count());
}
/**
* Define a join.
*
* @param ref reference
* @param target join target
* @return new instance of {@link QuerydslJoinBuilder}.
*/
<T> QuerydslJoinBuilder<ReactiveSpringDataMongodbQuery<K>, K, T> join(Path<T> ref, Path<T> target) {
return new QuerydslJoinBuilder<>(getQueryMixin(), ref, target);
}
/**
* Define a join.
*
* @param ref reference
* @param target join target
* @return new instance of {@link QuerydslJoinBuilder}.
*/
<T> QuerydslJoinBuilder<ReactiveSpringDataMongodbQuery<K>, K, T> join(CollectionPathBase<?, T, ?> ref,
Path<T> target) {
return new QuerydslJoinBuilder<>(getQueryMixin(), ref, target);
}
/**
* Define a constraint for an embedded object.
*
* @param collection collection must not be {@literal null}.
* @param target target must not be {@literal null}.
* @return new instance of {@link QuerydslAnyEmbeddedBuilder}.
*/
<T> QuerydslAnyEmbeddedBuilder<ReactiveSpringDataMongodbQuery<K>, K> anyEmbedded(
Path<? extends Collection<T>> collection, Path<T> target) {
return new QuerydslAnyEmbeddedBuilder<>(getQueryMixin(), collection);
}
protected Mono<Query> createQuery() {
QueryMetadata metadata = getQueryMixin().getMetadata();
return createQuery(createReactiveFilter(metadata), metadata.getProjection(), metadata.getModifiers(),
return createQuery(createFilter(metadata), metadata.getProjection(), metadata.getModifiers(),
metadata.getOrderBy());
}
@@ -128,8 +160,7 @@ class ReactiveSpringDataMongodbQuery<K> extends SpringDataMongodbQuerySupport<Re
.defaultIfEmpty(createQuery(null)) //
.map(it -> {
Document fields = createProjection(projection);
BasicQuery basicQuery = new BasicQuery(it, fields == null ? new Document() : fields);
BasicQuery basicQuery = new BasicQuery(it, createProjection(projection));
Integer limit = modifiers.getLimitAsInteger();
Integer offset = modifiers.getOffsetAsInteger();
@@ -148,11 +179,11 @@ class ReactiveSpringDataMongodbQuery<K> extends SpringDataMongodbQuerySupport<Re
});
}
protected Mono<Predicate> createReactiveFilter(QueryMetadata metadata) {
protected Mono<Predicate> createFilter(QueryMetadata metadata) {
if (!metadata.getJoins().isEmpty()) {
return createReactiveJoinFilter(metadata).map(it -> ExpressionUtils.allOf(metadata.getWhere(), it))
return createJoinFilter(metadata).map(it -> ExpressionUtils.allOf(metadata.getWhere(), it))
.switchIfEmpty(Mono.justOrEmpty(metadata.getWhere()));
}
@@ -166,7 +197,7 @@ class ReactiveSpringDataMongodbQuery<K> extends SpringDataMongodbQuerySupport<Re
* @return
*/
@SuppressWarnings("unchecked")
protected Mono<Predicate> createReactiveJoinFilter(QueryMetadata metadata) {
protected Mono<Predicate> createJoinFilter(QueryMetadata metadata) {
MultiValueMap<Expression<?>, Mono<Predicate>> predicates = new LinkedMultiValueMap<>();
List<JoinExpression> joins = metadata.getJoins();
@@ -199,7 +230,7 @@ class ReactiveSpringDataMongodbQuery<K> extends SpringDataMongodbQuerySupport<Re
Path<?> source = (Path) ((Operation) joins.get(0).getTarget()).getArg(0);
return allOf(predicates.get(source.getRoot())).onErrorResume(NoMatchException.class,
e -> Mono.just(ExpressionUtils.predicate(MongodbOps.NO_MATCH, e.source)));
e -> Mono.just(ExpressionUtils.predicate(QuerydslMongoOps.NO_MATCH, e.source)));
}
private Mono<Predicate> allOf(@Nullable Collection<Mono<Predicate>> predicates) {
@@ -215,8 +246,8 @@ class ReactiveSpringDataMongodbQuery<K> extends SpringDataMongodbQuerySupport<Re
*/
protected Flux<Object> getIds(Class<?> targetType, Mono<Predicate> condition) {
return condition.flatMapMany(it -> getJoinIds(targetType, it))
.switchIfEmpty(Flux.defer(() -> getJoinIds(targetType, (Predicate) null)));
return condition.flatMapMany(it -> getIds(targetType, it))
.switchIfEmpty(Flux.defer(() -> getIds(targetType, (Predicate) null)));
}
/**
@@ -226,18 +257,12 @@ class ReactiveSpringDataMongodbQuery<K> extends SpringDataMongodbQuerySupport<Re
* @param condition must not be {@literal null}.
* @return empty {@link List} if none found.
*/
protected Flux<Object> getJoinIds(Class<?> targetType, @Nullable Predicate condition) {
protected Flux<Object> getIds(Class<?> targetType, @Nullable Predicate condition) {
return createQuery(Mono.justOrEmpty(condition), null, QueryModifiers.EMPTY, Collections.emptyList())
.flatMapMany(query -> mongoOperations.findDistinct(query, "_id", targetType, Object.class));
}
@Override
protected List<Object> getIds(Class<?> aClass, Predicate predicate) {
throw new UnsupportedOperationException(
"Use create Flux<Object> getIds(Class<?> targetType, Mono<Predicate> condition)");
}
/**
* Marker exception to indicate no matches for a query using reference Id's.
*/

View File

@@ -36,7 +36,7 @@ import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.support.PageableExecutionUtils;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.data.util.StreamUtils;
import org.springframework.data.util.Streamable;
import org.springframework.lang.Nullable;
@@ -52,7 +52,6 @@ import com.mongodb.client.result.DeleteResult;
* @author Thomas Darimont
* @author Mark Paluch
* @author Mehran Behnam
* @author Jens Schauder
*/
public class SimpleMongoRepository<T, ID> implements MongoRepository<T, ID> {
@@ -74,10 +73,6 @@ public class SimpleMongoRepository<T, ID> implements MongoRepository<T, ID> {
this.mongoOperations = mongoOperations;
}
// -------------------------------------------------------------------------
// Methods from CrudRepository
// -------------------------------------------------------------------------
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#save(java.lang.Object)
@@ -141,27 +136,6 @@ public class SimpleMongoRepository<T, ID> implements MongoRepository<T, ID> {
entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#findAll()
*/
@Override
public List<T> findAll() {
return findAll(new Query());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#findAllById(java.lang.Iterable)
*/
@Override
public Iterable<T> findAllById(Iterable<ID> ids) {
Assert.notNull(ids, "The given Ids of entities not be null!");
return findAll(getIdQuery(ids));
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#count()
@@ -202,19 +176,6 @@ public class SimpleMongoRepository<T, ID> implements MongoRepository<T, ID> {
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#deleteAllById(java.lang.Iterable)
*/
@Override
public void deleteAllById(Iterable<? extends ID> ids) {
Assert.notNull(ids, "The given Iterable of ids must not be null!");
mongoOperations.remove(getIdQuery(ids), entityInformation.getJavaType(),
entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#delete(java.lang.Iterable)
@@ -222,7 +183,7 @@ public class SimpleMongoRepository<T, ID> implements MongoRepository<T, ID> {
@Override
public void deleteAll(Iterable<? extends T> entities) {
Assert.notNull(entities, "The given Iterable of entities must not be null!");
Assert.notNull(entities, "The given Iterable of entities not be null!");
entities.forEach(this::delete);
}
@@ -236,9 +197,27 @@ public class SimpleMongoRepository<T, ID> implements MongoRepository<T, ID> {
mongoOperations.remove(new Query(), entityInformation.getCollectionName());
}
// -------------------------------------------------------------------------
// Methods from PagingAndSortingRepository
// -------------------------------------------------------------------------
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#findAll()
*/
@Override
public List<T> findAll() {
return findAll(new Query());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#findAllById(java.lang.Iterable)
*/
@Override
public Iterable<T> findAllById(Iterable<ID> ids) {
Assert.notNull(ids, "The given Ids of entities not be null!");
return findAll(new Query(new Criteria(entityInformation.getIdAttribute())
.in(toCollection(ids))));
}
/*
* (non-Javadoc)
@@ -267,10 +246,6 @@ public class SimpleMongoRepository<T, ID> implements MongoRepository<T, ID> {
return findAll(new Query().with(sort));
}
// -------------------------------------------------------------------------
// Methods from MongoRepository
// -------------------------------------------------------------------------
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.MongoRepository#insert(java.lang.Object)
@@ -301,33 +276,23 @@ public class SimpleMongoRepository<T, ID> implements MongoRepository<T, ID> {
return new ArrayList<>(mongoOperations.insertAll(list));
}
// -------------------------------------------------------------------------
// Methods from QueryByExampleExecutor
// -------------------------------------------------------------------------
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.QueryByExampleExecutor#findOne(org.springframework.data.domain.Example)
* @see org.springframework.data.mongodb.repository.MongoRepository#findAllByExample(org.springframework.data.domain.Example, org.springframework.data.domain.Pageable)
*/
@Override
public <S extends T> Optional<S> findOne(Example<S> example) {
public <S extends T> Page<S> findAll(final Example<S> example, Pageable pageable) {
Assert.notNull(example, "Sample must not be null!");
Assert.notNull(pageable, "Pageable must not be null!");
Query query = new Query(new Criteria().alike(example)) //
.collation(entityInformation.getCollation());
.collation(entityInformation.getCollation()).with(pageable); //
return Optional
.ofNullable(mongoOperations.findOne(query, example.getProbeType(), entityInformation.getCollectionName()));
}
List<S> list = mongoOperations.find(query, example.getProbeType(), entityInformation.getCollectionName());
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.MongoRepository#findAllByExample(org.springframework.data.domain.Example)
*/
@Override
public <S extends T> List<S> findAll(Example<S> example) {
return findAll(example, Sort.unsorted());
return PageableExecutionUtils.getPage(list, pageable,
() -> mongoOperations.count(Query.of(query).limit(-1).skip(-1), example.getProbeType(), entityInformation.getCollectionName()));
}
/*
@@ -349,21 +314,27 @@ public class SimpleMongoRepository<T, ID> implements MongoRepository<T, ID> {
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.MongoRepository#findAllByExample(org.springframework.data.domain.Example, org.springframework.data.domain.Pageable)
* @see org.springframework.data.mongodb.repository.MongoRepository#findAllByExample(org.springframework.data.domain.Example)
*/
@Override
public <S extends T> Page<S> findAll(Example<S> example, Pageable pageable) {
public <S extends T> List<S> findAll(Example<S> example) {
return findAll(example, Sort.unsorted());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.QueryByExampleExecutor#findOne(org.springframework.data.domain.Example)
*/
@Override
public <S extends T> Optional<S> findOne(Example<S> example) {
Assert.notNull(example, "Sample must not be null!");
Assert.notNull(pageable, "Pageable must not be null!");
Query query = new Query(new Criteria().alike(example)) //
.collation(entityInformation.getCollation()).with(pageable); //
.collation(entityInformation.getCollation());
List<S> list = mongoOperations.find(query, example.getProbeType(), entityInformation.getCollectionName());
return PageableExecutionUtils.getPage(list, pageable,
() -> mongoOperations.count(Query.of(query).limit(-1).skip(-1), example.getProbeType(), entityInformation.getCollectionName()));
return Optional
.ofNullable(mongoOperations.findOne(query, example.getProbeType(), entityInformation.getCollectionName()));
}
/*
@@ -396,10 +367,6 @@ public class SimpleMongoRepository<T, ID> implements MongoRepository<T, ID> {
return mongoOperations.exists(query, example.getProbeType(), entityInformation.getCollectionName());
}
// -------------------------------------------------------------------------
// Utility methods
// -------------------------------------------------------------------------
private Query getIdQuery(Object id) {
return new Query(getIdCriteria(id));
}
@@ -408,12 +375,6 @@ public class SimpleMongoRepository<T, ID> implements MongoRepository<T, ID> {
return where(entityInformation.getIdAttribute()).is(id);
}
private Query getIdQuery(Iterable<? extends ID> ids) {
return new Query(new Criteria(entityInformation.getIdAttribute())
.in(toCollection(ids)));
}
private static <E> Collection<E> toCollection(Iterable<E> ids) {
return ids instanceof Collection ? (Collection<E>) ids
: StreamUtils.createStreamFromIterator(ids.iterator()).collect(Collectors.toList());
@@ -427,5 +388,4 @@ public class SimpleMongoRepository<T, ID> implements MongoRepository<T, ID> {
return mongoOperations.find(query, entityInformation.getJavaType(), entityInformation.getCollectionName());
}
}

View File

@@ -48,7 +48,6 @@ import com.mongodb.client.result.DeleteResult;
* @author Oliver Gierke
* @author Christoph Strobl
* @author Ruben J Garcia
* @author Jens Schauder
* @author Clément Petit
* @since 2.0
*/
@@ -67,9 +66,232 @@ public class SimpleReactiveMongoRepository<T, ID extends Serializable> implement
this.mongoOperations = mongoOperations;
}
// -------------------------------------------------------------------------
// Methods from ReactiveCrudRepository
// -------------------------------------------------------------------------
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#findById(java.lang.Object)
*/
@Override
public Mono<T> findById(ID id) {
Assert.notNull(id, "The given id must not be null!");
return mongoOperations.findById(id, entityInformation.getJavaType(), entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#findById(org.reactivestreams.Publisher)
*/
@Override
public Mono<T> findById(Publisher<ID> publisher) {
Assert.notNull(publisher, "The given id must not be null!");
return Mono.from(publisher).flatMap(
id -> mongoOperations.findById(id, entityInformation.getJavaType(), entityInformation.getCollectionName()));
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.ReactiveQueryByExampleExecutor#findOne(org.springframework.data.domain.Example)
*/
@Override
public <S extends T> Mono<S> findOne(Example<S> example) {
Assert.notNull(example, "Sample must not be null!");
Query query = new Query(new Criteria().alike(example)) //
.collation(entityInformation.getCollation()) //
.limit(2);
return mongoOperations.find(query, example.getProbeType(), entityInformation.getCollectionName()).buffer(2)
.map(vals -> {
if (vals.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1);
}
return vals.iterator().next();
}).next();
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#existsById(java.lang.Object)
*/
@Override
public Mono<Boolean> existsById(ID id) {
Assert.notNull(id, "The given id must not be null!");
return mongoOperations.exists(getIdQuery(id), entityInformation.getJavaType(),
entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#existsById(org.reactivestreams.Publisher)
*/
@Override
public Mono<Boolean> existsById(Publisher<ID> publisher) {
Assert.notNull(publisher, "The given id must not be null!");
return Mono.from(publisher).flatMap(id -> mongoOperations.exists(getIdQuery(id), entityInformation.getJavaType(),
entityInformation.getCollectionName()));
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.ReactiveQueryByExampleExecutor#exists(org.springframework.data.domain.Example)
*/
@Override
public <S extends T> Mono<Boolean> exists(Example<S> example) {
Assert.notNull(example, "Sample must not be null!");
Query query = new Query(new Criteria().alike(example)) //
.collation(entityInformation.getCollation());
return mongoOperations.exists(query, example.getProbeType(), entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveSortingRepository#findAll()
*/
@Override
public Flux<T> findAll() {
return findAll(new Query());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#findAllById(java.lang.Iterable)
*/
@Override
public Flux<T> findAllById(Iterable<ID> ids) {
Assert.notNull(ids, "The given Iterable of Id's must not be null!");
return findAll(new Query(new Criteria(entityInformation.getIdAttribute())
.in(toCollection(ids))));
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#findAllById(org.reactivestreams.Publisher)
*/
@Override
public Flux<T> findAllById(Publisher<ID> ids) {
Assert.notNull(ids, "The given Publisher of Id's must not be null!");
return Flux.from(ids).buffer().flatMap(this::findAllById);
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveSortingRepository#findAll(org.springframework.data.domain.Sort)
*/
@Override
public Flux<T> findAll(Sort sort) {
Assert.notNull(sort, "Sort must not be null!");
return findAll(new Query().with(sort));
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.ReactiveMongoRepository#findAll(org.springframework.data.domain.Example, org.springframework.data.domain.Sort)
*/
@Override
public <S extends T> Flux<S> findAll(Example<S> example, Sort sort) {
Assert.notNull(example, "Sample must not be null!");
Assert.notNull(sort, "Sort must not be null!");
Query query = new Query(new Criteria().alike(example)) //
.collation(entityInformation.getCollation()) //
.with(sort);
return mongoOperations.find(query, example.getProbeType(), entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.ReactiveMongoRepository#findAll(org.springframework.data.domain.Example)
*/
@Override
public <S extends T> Flux<S> findAll(Example<S> example) {
Assert.notNull(example, "Example must not be null!");
return findAll(example, Sort.unsorted());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#count()
*/
@Override
public Mono<Long> count() {
return mongoOperations.count(new Query(), entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.ReactiveQueryByExampleExecutor#count(org.springframework.data.domain.Example)
*/
@Override
public <S extends T> Mono<Long> count(Example<S> example) {
Assert.notNull(example, "Sample must not be null!");
Query query = new Query(new Criteria().alike(example)) //
.collation(entityInformation.getCollation());
return mongoOperations.count(query, example.getProbeType(), entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.ReactiveMongoRepository#insert(java.lang.Object)
*/
@Override
public <S extends T> Mono<S> insert(S entity) {
Assert.notNull(entity, "Entity must not be null!");
return mongoOperations.insert(entity, entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.ReactiveMongoRepository#insert(java.lang.Iterable)
*/
@Override
public <S extends T> Flux<S> insert(Iterable<S> entities) {
Assert.notNull(entities, "The given Iterable of entities must not be null!");
Collection<S> source = toCollection(entities);
return source.isEmpty() ? Flux.empty() : mongoOperations.insertAll(source);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.ReactiveMongoRepository#insert(org.reactivestreams.Publisher)
*/
@Override
public <S extends T> Flux<S> insert(Publisher<S> entities) {
Assert.notNull(entities, "The given Publisher of entities must not be null!");
return Flux.from(entities).flatMap(entity -> mongoOperations.insert(entity, entityInformation.getCollectionName()));
}
/*
* (non-Javadoc)
@@ -117,100 +339,6 @@ public class SimpleReactiveMongoRepository<T, ID extends Serializable> implement
mongoOperations.save(entity, entityInformation.getCollectionName()));
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#findById(java.lang.Object)
*/
@Override
public Mono<T> findById(ID id) {
Assert.notNull(id, "The given id must not be null!");
return mongoOperations.findById(id, entityInformation.getJavaType(), entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#findById(org.reactivestreams.Publisher)
*/
@Override
public Mono<T> findById(Publisher<ID> publisher) {
Assert.notNull(publisher, "The given id must not be null!");
return Mono.from(publisher).flatMap(
id -> mongoOperations.findById(id, entityInformation.getJavaType(), entityInformation.getCollectionName()));
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#existsById(java.lang.Object)
*/
@Override
public Mono<Boolean> existsById(ID id) {
Assert.notNull(id, "The given id must not be null!");
return mongoOperations.exists(getIdQuery(id), entityInformation.getJavaType(),
entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#existsById(org.reactivestreams.Publisher)
*/
@Override
public Mono<Boolean> existsById(Publisher<ID> publisher) {
Assert.notNull(publisher, "The given id must not be null!");
return Mono.from(publisher).flatMap(id -> mongoOperations.exists(getIdQuery(id), entityInformation.getJavaType(),
entityInformation.getCollectionName()));
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveSortingRepository#findAll()
*/
@Override
public Flux<T> findAll() {
return findAll(new Query());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#findAllById(java.lang.Iterable)
*/
@Override
public Flux<T> findAllById(Iterable<ID> ids) {
Assert.notNull(ids, "The given Iterable of Id's must not be null!");
return findAll(getIdQuery(ids));
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#findAllById(org.reactivestreams.Publisher)
*/
@Override
public Flux<T> findAllById(Publisher<ID> ids) {
Assert.notNull(ids, "The given Publisher of Id's must not be null!");
return Flux.from(ids).buffer().flatMap(this::findAllById);
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#count()
*/
@Override
public Mono<Long> count() {
return mongoOperations.count(new Query(), entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#deleteById(java.lang.Object)
@@ -266,19 +394,6 @@ public class SimpleReactiveMongoRepository<T, ID extends Serializable> implement
return remove.then();
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#deleteAllById(java.lang.Iterable)
*/
@Override
public Mono<Void> deleteAllById(Iterable<? extends ID> ids) {
Assert.notNull(ids, "The given Iterable of Id's must not be null!");
return mongoOperations
.remove(getIdQuery(ids), entityInformation.getJavaType(), entityInformation.getCollectionName()).then();
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#deleteAll(java.lang.Iterable)
@@ -288,14 +403,7 @@ public class SimpleReactiveMongoRepository<T, ID extends Serializable> implement
Assert.notNull(entities, "The given Iterable of entities must not be null!");
Collection<?> idCollection = StreamUtils.createStreamFromIterator(entities.iterator()).map(entityInformation::getId)
.collect(Collectors.toList());
Criteria idsInCriteria = where(entityInformation.getIdAttribute()).in(idCollection);
return mongoOperations
.remove(new Query(idsInCriteria), entityInformation.getJavaType(), entityInformation.getCollectionName())
.then();
return Flux.fromIterable(entities).flatMap(this::delete).then();
}
/*
@@ -322,150 +430,6 @@ public class SimpleReactiveMongoRepository<T, ID extends Serializable> implement
return mongoOperations.remove(new Query(), entityInformation.getCollectionName()).then(Mono.empty());
}
// -------------------------------------------------------------------------
// Methods from ReactiveSortingRepository
// -------------------------------------------------------------------------
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveSortingRepository#findAll(org.springframework.data.domain.Sort)
*/
@Override
public Flux<T> findAll(Sort sort) {
Assert.notNull(sort, "Sort must not be null!");
return findAll(new Query().with(sort));
}
// -------------------------------------------------------------------------
// Methods from ReactiveMongoRepository
// -------------------------------------------------------------------------
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.ReactiveMongoRepository#insert(java.lang.Object)
*/
@Override
public <S extends T> Mono<S> insert(S entity) {
Assert.notNull(entity, "Entity must not be null!");
return mongoOperations.insert(entity, entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.ReactiveMongoRepository#insert(java.lang.Iterable)
*/
@Override
public <S extends T> Flux<S> insert(Iterable<S> entities) {
Assert.notNull(entities, "The given Iterable of entities must not be null!");
Collection<S> source = toCollection(entities);
return source.isEmpty() ? Flux.empty() : mongoOperations.insertAll(source);
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.ReactiveMongoRepository#insert(org.reactivestreams.Publisher)
*/
@Override
public <S extends T> Flux<S> insert(Publisher<S> entities) {
Assert.notNull(entities, "The given Publisher of entities must not be null!");
return Flux.from(entities).flatMap(entity -> mongoOperations.insert(entity, entityInformation.getCollectionName()));
}
// -------------------------------------------------------------------------
// Methods from ReactiveMongoRepository
// -------------------------------------------------------------------------
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.ReactiveQueryByExampleExecutor#findOne(org.springframework.data.domain.Example)
*/
@Override
public <S extends T> Mono<S> findOne(Example<S> example) {
Assert.notNull(example, "Sample must not be null!");
Query query = new Query(new Criteria().alike(example)) //
.collation(entityInformation.getCollation()) //
.limit(2);
return mongoOperations.find(query, example.getProbeType(), entityInformation.getCollectionName()).buffer(2)
.map(vals -> {
if (vals.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1);
}
return vals.iterator().next();
}).next();
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.ReactiveMongoRepository#findAll(org.springframework.data.domain.Example)
*/
@Override
public <S extends T> Flux<S> findAll(Example<S> example) {
Assert.notNull(example, "Example must not be null!");
return findAll(example, Sort.unsorted());
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.ReactiveMongoRepository#findAll(org.springframework.data.domain.Example, org.springframework.data.domain.Sort)
*/
@Override
public <S extends T> Flux<S> findAll(Example<S> example, Sort sort) {
Assert.notNull(example, "Sample must not be null!");
Assert.notNull(sort, "Sort must not be null!");
Query query = new Query(new Criteria().alike(example)) //
.collation(entityInformation.getCollation()) //
.with(sort);
return mongoOperations.find(query, example.getProbeType(), entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.ReactiveQueryByExampleExecutor#count(org.springframework.data.domain.Example)
*/
@Override
public <S extends T> Mono<Long> count(Example<S> example) {
Assert.notNull(example, "Sample must not be null!");
Query query = new Query(new Criteria().alike(example)) //
.collation(entityInformation.getCollation());
return mongoOperations.count(query, example.getProbeType(), entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.ReactiveQueryByExampleExecutor#exists(org.springframework.data.domain.Example)
*/
@Override
public <S extends T> Mono<Boolean> exists(Example<S> example) {
Assert.notNull(example, "Sample must not be null!");
Query query = new Query(new Criteria().alike(example)) //
.collation(entityInformation.getCollation());
return mongoOperations.exists(query, example.getProbeType(), entityInformation.getCollectionName());
}
private Query getIdQuery(Object id) {
return new Query(getIdCriteria(id));
}
@@ -474,10 +438,6 @@ public class SimpleReactiveMongoRepository<T, ID extends Serializable> implement
return where(entityInformation.getIdAttribute()).is(id);
}
private Query getIdQuery(Iterable<? extends ID> ids) {
return new Query(where(entityInformation.getIdAttribute()).in(toCollection(ids)));
}
private static <E> Collection<E> toCollection(Iterable<E> ids) {
return ids instanceof Collection ? (Collection<E>) ids
: StreamUtils.createStreamFromIterator(ids.iterator()).collect(Collectors.toList());

View File

@@ -15,27 +15,7 @@
*/
package org.springframework.data.mongodb.repository.support;
import java.util.Collections;
import java.util.List;
import org.bson.Document;
import org.springframework.data.mongodb.core.ExecutableFindOperation;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.lang.Nullable;
import com.mysema.commons.lang.CloseableIterator;
import com.mysema.commons.lang.EmptyCloseableIterator;
import com.querydsl.core.Fetchable;
import com.querydsl.core.QueryMetadata;
import com.querydsl.core.QueryModifiers;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Predicate;
import com.querydsl.mongodb.document.MongodbDocumentSerializer;
/**
* Spring Data specific simple {@link com.querydsl.core.Fetchable} {@link com.querydsl.core.SimpleQuery Query}
@@ -45,13 +25,7 @@ import com.querydsl.mongodb.document.MongodbDocumentSerializer;
* @author Mark Paluch
* @author Christoph Strobl
*/
public class SpringDataMongodbQuery<T> extends SpringDataMongodbQuerySupport<SpringDataMongodbQuery<T>>
implements Fetchable<T> {
private final Class<T> entityClass;
private final String collection;
private final MongoOperations mongoOperations;
private final ExecutableFindOperation.FindWithProjection<T> find;
public class SpringDataMongodbQuery<T> extends QuerydslFetchableMongodbQuery<T, SpringDataMongodbQuery<T>> {
/**
* Creates a new {@link SpringDataMongodbQuery}.
@@ -59,7 +33,7 @@ public class SpringDataMongodbQuery<T> extends SpringDataMongodbQuerySupport<Spr
* @param operations must not be {@literal null}.
* @param type must not be {@literal null}.
*/
public SpringDataMongodbQuery(MongoOperations operations, Class<? extends T> type) {
public SpringDataMongodbQuery(final MongoOperations operations, final Class<? extends T> type) {
this(operations, type, operations.getCollectionName(type));
}
@@ -70,174 +44,9 @@ public class SpringDataMongodbQuery<T> extends SpringDataMongodbQuerySupport<Spr
* @param type must not be {@literal null}.
* @param collectionName must not be {@literal null} or empty.
*/
public SpringDataMongodbQuery(MongoOperations operations, Class<? extends T> type,
public SpringDataMongodbQuery(final MongoOperations operations, final Class<? extends T> type,
String collectionName) {
this(new SpringDataMongodbSerializer(operations.getConverter()), operations, type, collectionName);
super(new SpringDataMongodbSerializer(operations.getConverter()), type, collectionName, operations);
}
private SpringDataMongodbQuery(MongodbDocumentSerializer serializer, MongoOperations operations,
Class<? extends T> type, String collectionName) {
super(serializer);
this.entityClass = (Class<T>) type;
this.collection = collectionName;
this.mongoOperations = operations;
this.find = mongoOperations.query(this.entityClass).inCollection(collection);
}
/*
* (non-Javadoc)
* @see com.querydsl.core.Fetchable#iterable()
*/
@Override
public CloseableIterator<T> iterate() {
try {
org.springframework.data.util.CloseableIterator<? extends T> stream = mongoOperations.stream(createQuery(),
entityClass, collection);
return new CloseableIterator<T>() {
@Override
public boolean hasNext() {
return stream.hasNext();
}
@Override
public T next() {
return stream.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("Cannot remove from iterator while streaming data.");
}
@Override
public void close() {
stream.close();
}
};
} catch (RuntimeException e) {
return handleException(e, new EmptyCloseableIterator<>());
}
}
/*
* (non-Javadoc)
* @see com.querydsl.core.Fetchable#fetch()
*/
@Override
public List<T> fetch() {
try {
return find.matching(createQuery()).all();
} catch (RuntimeException e) {
return handleException(e, Collections.emptyList());
}
}
/*
* (non-Javadoc)
* @see com.querydsl.core.Fetchable#fetchFirst()
*/
@Override
public T fetchFirst() {
try {
return find.matching(createQuery()).firstValue();
} catch (RuntimeException e) {
return handleException(e, null);
}
}
/*
* (non-Javadoc)
* @see com.querydsl.core.Fetchable#fetchOne()
*/
@Override
public T fetchOne() {
try {
return find.matching(createQuery()).oneValue();
} catch (RuntimeException e) {
return handleException(e, null);
}
}
/*
* (non-Javadoc)
* @see com.querydsl.core.Fetchable#fetchResults()
*/
@Override
public QueryResults<T> fetchResults() {
long total = fetchCount();
return total > 0L ? new QueryResults<>(fetch(), getQueryMixin().getMetadata().getModifiers(), total)
: QueryResults.emptyResults();
}
/*
* (non-Javadoc)
* @see com.querydsl.core.Fetchable#fetchCount()
*/
@Override
public long fetchCount() {
try {
return find.matching(Query.of(createQuery()).skip(-1).limit(-1)).count();
} catch (RuntimeException e) {
return handleException(e, 0L);
}
}
protected org.springframework.data.mongodb.core.query.Query createQuery() {
QueryMetadata metadata = getQueryMixin().getMetadata();
return createQuery(createFilter(metadata), metadata.getProjection(), metadata.getModifiers(),
metadata.getOrderBy());
}
protected org.springframework.data.mongodb.core.query.Query createQuery(@Nullable Predicate filter,
@Nullable Expression<?> projection, QueryModifiers modifiers, List<OrderSpecifier<?>> orderBy) {
Document fields = createProjection(projection);
BasicQuery basicQuery = new BasicQuery(createQuery(filter), fields == null ? new Document() : fields);
Integer limit = modifiers.getLimitAsInteger();
Integer offset = modifiers.getOffsetAsInteger();
if (limit != null) {
basicQuery.limit(limit);
}
if (offset != null) {
basicQuery.skip(offset);
}
if (orderBy.size() > 0) {
basicQuery.setSortObject(createSort(orderBy));
}
return basicQuery;
}
/**
* Fetch the list of ids matching a given condition.
*
* @param targetType must not be {@literal null}.
* @param condition must not be {@literal null}.
* @return empty {@link List} if none found.
*/
protected List<Object> getIds(Class<?> targetType, Predicate condition) {
Query query = createQuery(condition, null, QueryModifiers.EMPTY, Collections.emptyList());
return mongoOperations.findDistinct(query, "_id", targetType, Object.class);
}
private static <T> T handleException(RuntimeException e, T defaultValue) {
if (e.getClass().getName().endsWith("$NoResults")) {
return defaultValue;
}
throw e;
}
}

View File

@@ -1,142 +0,0 @@
/*
* Copyright 2021 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.repository.support;
import java.util.List;
import org.bson.Document;
import org.bson.codecs.DocumentCodec;
import org.bson.json.JsonMode;
import org.bson.json.JsonWriterSettings;
import org.springframework.beans.DirectFieldAccessor;
import com.mongodb.MongoClientSettings;
import com.querydsl.core.support.QueryMixin;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.mongodb.document.AbstractMongodbQuery;
import com.querydsl.mongodb.document.MongodbDocumentSerializer;
/**
* Support query type to augment Spring Data-specific {@link #toString} representations and
* {@link org.springframework.data.domain.Sort} creation.
*
* @author Mark Paluch
* @since 3.3
*/
abstract class SpringDataMongodbQuerySupport<Q extends SpringDataMongodbQuerySupport<Q>>
extends AbstractMongodbQuery<Q> {
private final QueryMixin<Q> superQueryMixin;
private static final JsonWriterSettings JSON_WRITER_SETTINGS = JsonWriterSettings.builder().outputMode(JsonMode.SHELL)
.build();
private final MongodbDocumentSerializer serializer;
@SuppressWarnings("unchecked")
SpringDataMongodbQuerySupport(MongodbDocumentSerializer serializer) {
super(serializer);
this.serializer = serializer;
DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(this);
this.superQueryMixin = (QueryMixin<Q>) fieldAccessor.getPropertyValue("queryMixin");
}
/**
* Returns the {@literal Mongo Shell} representation of the query. <br />
* The following query
*
* <pre class="code">
*
* where(p.lastname.eq("Matthews")).orderBy(p.firstname.asc()).offset(1).limit(5);
* </pre>
*
* results in
*
* <pre class="code">
*
* find({"lastname" : "Matthews"}).sort({"firstname" : 1}).skip(1).limit(5)
* </pre>
*
* Note that encoding to {@link String} may fail when using data types that cannot be encoded or DBRef's without an
* identifier.
*
* @return never {@literal null}.
*/
@Override
public String toString() {
Document projection = createProjection(getQueryMixin().getMetadata().getProjection());
Document sort = createSort(getQueryMixin().getMetadata().getOrderBy());
DocumentCodec codec = new DocumentCodec(MongoClientSettings.getDefaultCodecRegistry());
StringBuilder sb = new StringBuilder("find(" + asDocument().toJson(JSON_WRITER_SETTINGS, codec));
if (projection != null && projection.isEmpty()) {
sb.append(", ").append(projection.toJson(JSON_WRITER_SETTINGS, codec));
}
sb.append(")");
if (!sort.isEmpty()) {
sb.append(".sort(").append(sort.toJson(JSON_WRITER_SETTINGS, codec)).append(")");
}
if (getQueryMixin().getMetadata().getModifiers().getOffset() != null) {
sb.append(".skip(").append(getQueryMixin().getMetadata().getModifiers().getOffset()).append(")");
}
if (getQueryMixin().getMetadata().getModifiers().getLimit() != null) {
sb.append(".limit(").append(getQueryMixin().getMetadata().getModifiers().getLimit()).append(")");
}
return sb.toString();
}
/**
* Get the where definition as a Document instance
*
* @return
*/
public Document asDocument() {
return createQuery(getQueryMixin().getMetadata().getWhere());
}
/**
* Obtain the {@literal Mongo Shell} json query representation.
*
* @return never {@literal null}.
*/
public String toJson() {
return toJson(JSON_WRITER_SETTINGS);
}
/**
* Obtain the json query representation applying given {@link JsonWriterSettings settings}.
*
* @param settings must not be {@literal null}.
* @return never {@literal null}.
*/
public String toJson(JsonWriterSettings settings) {
return asDocument().toJson(settings);
}
/**
* Compute the sort {@link Document} from the given list of {@link OrderSpecifier order specifiers}.
*
* @param orderSpecifiers can be {@literal null}.
* @return an empty {@link Document} if predicate is {@literal null}.
* @see MongodbDocumentSerializer#toSort(List)
*/
protected Document createSort(List<OrderSpecifier<?>> orderSpecifiers) {
return serializer.toSort(orderSpecifiers);
}
}

View File

@@ -22,7 +22,6 @@ import java.util.Set;
import java.util.regex.Pattern;
import org.bson.Document;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.convert.QueryMapper;
@@ -40,7 +39,6 @@ import com.querydsl.core.types.Path;
import com.querydsl.core.types.PathMetadata;
import com.querydsl.core.types.PathType;
import com.querydsl.mongodb.MongodbSerializer;
import com.querydsl.mongodb.document.MongodbDocumentSerializer;
/**
* Custom {@link MongodbSerializer} to take mapping information into account when building keys for constraints.

View File

@@ -17,14 +17,12 @@ package org.springframework.data.mongodb.util;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.StringJoiner;
import java.util.function.Function;
import java.util.stream.StreamSupport;
import org.bson.BSONObject;
import org.bson.BsonBinary;
import org.bson.BsonBoolean;
import org.bson.BsonDouble;
@@ -38,11 +36,11 @@ import org.bson.codecs.DocumentCodec;
import org.bson.conversions.Bson;
import org.bson.json.JsonParseException;
import org.bson.types.ObjectId;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.CodecRegistryProvider;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
@@ -52,8 +50,6 @@ import com.mongodb.DBRef;
import com.mongodb.MongoClientSettings;
/**
* Internal API for operations on {@link Bson} elements that can be either {@link Document} or {@link DBObject}.
*
* @author Christoph Strobl
* @author Mark Paluch
* @since 2.0
@@ -74,9 +70,6 @@ public class BsonUtils {
if (bson instanceof BasicDBObject) {
return ((BasicDBObject) bson);
}
if (bson instanceof DBObject) {
return ((DBObject) bson).toMap();
}
return (Map) bson.toBsonDocument(Document.class, MongoClientSettings.getDefaultCodecRegistry());
}
@@ -84,110 +77,14 @@ public class BsonUtils {
public static void addToMap(Bson bson, String key, @Nullable Object value) {
if (bson instanceof Document) {
((Document) bson).put(key, value);
return;
}
if (bson instanceof BSONObject) {
((BSONObject) bson).put(key, value);
if (bson instanceof DBObject) {
((DBObject) bson).put(key, value);
return;
}
throw new IllegalArgumentException(String.format(
"Cannot add key/value pair to %s. as map. Given Bson must be a Document or BSONObject!", bson.getClass()));
}
/**
* Add all entries from the given {@literal source} {@link Map} to the {@literal target}.
*
* @param target must not be {@literal null}.
* @param source must not be {@literal null}.
* @since 3.2
*/
public static void addAllToMap(Bson target, Map<String, ?> source) {
if (target instanceof Document) {
((Document) target).putAll(source);
return;
}
if (target instanceof BSONObject) {
((BSONObject) target).putAll(source);
return;
}
throw new IllegalArgumentException(
String.format("Cannot add all to %s. Given Bson must be a Document or BSONObject.", target.getClass()));
}
/**
* Check if a given entry (key/value pair) is present in the given {@link Bson}.
*
* @param bson must not be {@literal null}.
* @param key must not be {@literal null}.
* @param value can be {@literal null}.
* @return {@literal true} if (key/value pair) is present.
* @since 3.2
*/
public static boolean contains(Bson bson, String key, @Nullable Object value) {
if (bson instanceof Document) {
Document doc = (Document) bson;
return doc.containsKey(key) && ObjectUtils.nullSafeEquals(doc.get(key), value);
}
if (bson instanceof BSONObject) {
BSONObject bsonObject = (BSONObject) bson;
return bsonObject.containsField(key) && ObjectUtils.nullSafeEquals(bsonObject.get(key), value);
}
Map<String, Object> map = asMap(bson);
return map.containsKey(key) && ObjectUtils.nullSafeEquals(map.get(key), value);
}
/**
* Remove {@code _id : null} from the given {@link Bson} if present.
*
* @param bson must not be {@literal null}.
* @since 3.2
*/
public static boolean removeNullId(Bson bson) {
if (!contains(bson, "_id", null)) {
return false;
}
removeFrom(bson, "_id");
return true;
}
/**
* Remove the given {@literal key} from the {@link Bson} value.
*
* @param bson must not be {@literal null}.
* @param key must not be {@literal null}.
* @since 3.2
*/
static void removeFrom(Bson bson, String key) {
if (bson instanceof Document) {
((Document) bson).remove(key);
return;
}
if (bson instanceof BSONObject) {
((BSONObject) bson).removeField(key);
return;
}
throw new IllegalArgumentException(
String.format("Cannot remove from %s. Given Bson must be a Document or BSONObject.", bson.getClass()));
throw new IllegalArgumentException("o_O what's that? Cannot add value to " + bson.getClass());
}
/**
@@ -349,13 +246,7 @@ public class BsonUtils {
* @since 3.0
*/
public static boolean isJsonDocument(@Nullable String value) {
if(!StringUtils.hasText(value)) {
return false;
}
String potentialJson = value.trim();
return potentialJson.startsWith("{") && potentialJson.endsWith("}");
return StringUtils.hasText(value) && (value.startsWith("{") && value.endsWith("}"));
}
/**
@@ -494,67 +385,6 @@ public class BsonUtils {
return null;
}
/**
* Returns the given source object as {@link Bson}, i.e. {@link Document}s and maps as is or throw
* {@link IllegalArgumentException}.
*
* @param source
* @return the converted/casted source object.
* @throws IllegalArgumentException if {@code source} cannot be converted/cast to {@link Bson}.
* @since 3.2.3
* @see #supportsBson(Object)
*/
@SuppressWarnings("unchecked")
public static Bson asBson(Object source) {
if (source instanceof Document) {
return (Document) source;
}
if (source instanceof BasicDBObject) {
return (BasicDBObject) source;
}
if (source instanceof DBObject) {
return new Document(((DBObject) source).toMap());
}
if (source instanceof Map) {
return new Document((Map<String, Object>) source);
}
throw new IllegalArgumentException(String.format("Cannot convert %s to Bson", source));
}
/**
* Returns the given source can be used/converted as {@link Bson}.
*
* @param source
* @return {@literal true} if the given source can be converted to {@link Bson}.
* @since 3.2.3
*/
public static boolean supportsBson(Object source) {
return source instanceof DBObject || source instanceof Map;
}
/**
* Returns given object as {@link Collection}. Will return the {@link Collection} as is if the source is a
* {@link Collection} already, will convert an array into a {@link Collection} or simply create a single element
* collection for everything else.
*
* @param source must not be {@literal null}.
* @return never {@literal null}.
* @since 3.2
*/
public static Collection<?> asCollection(Object source) {
if (source instanceof Collection) {
return (Collection<?>) source;
}
return source.getClass().isArray() ? CollectionUtils.arrayToList(source) : Collections.singleton(source);
}
@Nullable
private static String toJson(@Nullable Object value) {

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