Skip to content

Commit f98048e

Browse files
committed
final
1 parent d857cda commit f98048e

File tree

5 files changed

+103
-87
lines changed

5 files changed

+103
-87
lines changed

source/includes/integrations/spring-data-tutorial-code/main/java/CustomProductsRepository.java

Lines changed: 0 additions & 8 deletions
This file was deleted.
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,18 @@
1010

1111
// start-application
1212
@SpringBootApplication
13-
public class SpringDataBulkInsertApplication implements CommandLineRunner {
13+
public class MyProjectName implements CommandLineRunner {
1414

1515
@Value("${documentCount}")
1616
private int count;
1717
private static final Logger LOG = LoggerFactory
18-
.getLogger(SpringDataBulkInsertApplication.class);
18+
.getLogger(MyProjectName.class);
1919

2020
@Autowired
21-
private CustomProductsRepository repository;
21+
private ProductRepository repository;
2222

2323
public static void main(String[] args) {
24-
SpringApplication.run(SpringDataBulkInsertApplication.class, args);
24+
SpringApplication.run(MyProjectName.class, args);
2525
}
2626

2727
@Override
Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,27 @@
22

33
import com.mongodb.WriteConcern;
44
import com.mongodb.bulk.BulkWriteResult;
5-
import com.mongodb.client.result.UpdateResult;
65
import org.slf4j.Logger;
76
import org.slf4j.LoggerFactory;
87
import org.springframework.beans.factory.annotation.Autowired;
98
import org.springframework.data.mongodb.core.BulkOperations;
109
import org.springframework.data.mongodb.core.MongoTemplate;
11-
import org.springframework.data.mongodb.core.query.Criteria;
12-
import org.springframework.data.mongodb.core.query.Query;
13-
import org.springframework.data.mongodb.core.query.Update;
1410
import org.springframework.stereotype.Component;
1511

1612
import java.time.Duration;
1713
import java.time.Instant;
1814

19-
// start-customproductsrepoimpl
15+
// start-productrepo
2016
@Component
21-
public class CustomProductsRepositoryImpl implements CustomProductsRepository {
17+
public class ProductRepository {
2218

2319
private static final Logger LOG = LoggerFactory
24-
.getLogger(CustomProductsRepository.class);
20+
.getLogger(ProductRepository.class);
2521

2622
private final MongoTemplate mongoTemplate;
2723

2824
@Autowired
29-
public CustomProductsRepositoryImpl(MongoTemplate mongoTemplate){
25+
public ProductRepository(MongoTemplate mongoTemplate){
3026
this.mongoTemplate = mongoTemplate;
3127
}
3228

@@ -65,4 +61,4 @@ public int bulkInsertProducts(int count) {
6561
return bulkWriteResult.getInsertedCount();
6662
}
6763
}
68-
// end-customproductsrepoimpl
64+
// end-productrepo
Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
11

2+
# start-mongoconfig-properties
23
mongodb.database=bulk
3-
44
mongodb.uri=<connection string>
5-
mongodb.atlas=1
6-
7-
truststore.path=/etc/ssl/truststore.jks
8-
truststore.pwd=P4ssw0rd
9-
105
documentCount=25000
6+
# end-mongoconfig-properties

source/integrations/spring-data-integration.txt

Lines changed: 92 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -29,18 +29,31 @@ MongoDB <https://spring.io/projects/spring-data-mongodb>`__ with the
2929
Spring Data MongoDB
3030
~~~~~~~~~~~~~~~~~~~
3131

32-
Spring Data MongoDB is a third-party Java ORM for MongoDB. The Spring Data
33-
project provides a familiar and consistent Spring-based programming model while
34-
enabling MongoDB-specific features and capabilities. Spring Data MongoDB uses a
35-
POJO-centric model for interacting with collections and writing repository-style
36-
data access layers.
32+
Spring Data MongoDB is the official Spring Data ODM for MongoDB. It allows you to
33+
interact with MongoDB by using plain old Java objects (POJOs) and repository
34+
abstraction. It supports MongoDB-specific features like dynamic queries,
35+
indexing, and nested document mapping while reducing boilerplate code such as
36+
manual ``find()`` and ``update()`` calls.
37+
38+
Dependency Injection
39+
~~~~~~~~~~~~~~~~~~~~
40+
41+
Dependency injection (DI) is a core principle of the Spring Framework. It
42+
allows objects, called beans, to be created and managed by the Spring container,
43+
then injected into other beans that use them. This is distinct from typical
44+
object-oriented development where classes are responsible for initializing and
45+
constructing the objects they use.
46+
47+
For more information about dependency injection, see the `Dependency
48+
Injection <https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html>`__
49+
page of the Spring Framework documentation.
3750

3851
The Spring Data BulkOperations Interface
3952
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4053

4154
BulkOperations is an Spring Framework Data interface that contains a list of write
42-
operations that can be applied to your database. They can be any combination of
43-
the following operations which map to similar {+driver-short+} operations:
55+
operations that can be applied to your database. It can handle any combination of
56+
the following operations which map to similar {+driver-long+} operations:
4457

4558
- ``insert``
4659
- ``updateOne``
@@ -50,10 +63,10 @@ the following operations which map to similar {+driver-short+} operations:
5063
- ``deleteMany``
5164
- ``upsert``
5265

53-
A BulkOperation can be ordered or unordered. Ordered operations will be applied
54-
sequentially and if an error is detected, will return with an error code.
55-
Unordered operations will be applied in parallel, which means they can be
56-
faster. However, you must check if there were errors during the operations.
66+
A BulkOperation can be ordered or unordered. Ordered bulk operations run operations
67+
sequentially, and if an error is detected, return with an error code.
68+
Unordered operations are run in parallel, which means they are typically faster
69+
faster. However, you must manually check if there were errors during the operations.
5770

5871
For more information about bulk operations, see the following resources:
5972

@@ -72,7 +85,7 @@ You can find the completed sample app for this tutorial in the
7285

7386
.. note:: Imports Not specified
7487

75-
The import statements required for the classes in the tutorial have not been included. See the :github:`GitHub repository</mongodb-developer/SpringDataMongoBulkInsert>` for complete files.
88+
The import statements required for the files in the tutorial have not been included on the page. See the :github:`GitHub repository</mongodb-developer/SpringDataMongoBulkInsert>` for complete files.
7689

7790
Prerequisites
7891
~~~~~~~~~~~~~
@@ -81,11 +94,9 @@ Ensure you have the following components installed and set up before you start
8194
this tutorial:
8295

8396
- `Java 8 or later <https://www.oracle.com/java/technologies/downloads/>`__
84-
- A MongoDB Atlas cluster
85-
To learn how to set up a cluster, see the :ref:`Getting Started
86-
<java-get-started>`__ guide for more information.
87-
- `Spring Boot application setup <https://spring.io/guides/gs/spring-boot>`__
88-
- Maven for dependency management
97+
- `Maven <https://maven.apache.org/>`__
98+
- A :atlas:`MongoDB Atlas cluster </getting-started?tck=docs_driver_java>`
99+
- A new `Spring Boot application <https://spring.io/guides/gs/spring-boot>`__
89100

90101
Add Dependencies
91102
~~~~~~~~~~~~~~~~
@@ -97,16 +108,26 @@ the `Requirements
97108
of the Spring Data MongoDB documentation, and the :ref:`Compatibility
98109
<java-compatibility-tables>` page of this guide.
99110

100-
Add the dependency to your ``pom.xml``:
111+
.. note::
112+
113+
If you used the `Spring Initializr <https://start.spring.io/>`__ or a clone of the :github:`Spring Boot sample project <spring-guides/gs-spring-boot>` to create your project, versioning compatibility has already been accounted for, and the ``spring-boot-starter-data-mongodb`` component will already be included in your ``pom.xml`` file.
114+
115+
Add the dependencies to your ``pom.xml``:
101116

102117
.. code-block:: xml
103118

104-
<dependencies>
105119
<dependency>
106-
<groupId>org.springframework.boot</groupId>
107-
<artifactId>spring-boot-starter-data-mongodb</artifactId>
108-
<version/> // Add as necessary
120+
<groupId>org.springframework.boot</groupId>
121+
<artifactId>spring-boot-starter-data-mongodb</artifactId>
122+
<version>3.2.5 </version>
109123
</dependency>
124+
<dependency>
125+
<groupId>net.datafaker</groupId>
126+
<artifactId>datafaker</artifactId>
127+
<version>2.4.3</version>
128+
</dependency>
129+
130+
The ``datafaker`` dependency is used to generate a large quantity of Product objects.
110131

111132
MongoClient Configuration
112133
~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -138,13 +159,22 @@ following code to a ``MongoConfig.java`` file:
138159
:language: java
139160
:dedent:
140161

141-
Ensure that your connection string (``mongodb.database``) and
142-
database name (``mongodb.database``) are set in your environment variables. For
162+
Set the values of your connection string (``mongodb.uri``),
163+
database name (``mongodb.database``), and bulk operation count (``documentCount``) in your ``application.properties`` file:
164+
165+
.. literalinclude:: /includes/integrations/spring-data-tutorial-code/main/resources/application.properties
166+
:start-after: # start-mongoconfig-properties
167+
:end-before: # end-mongoconfig-properties
168+
:language: console
169+
:dedent:
170+
171+
This tutorial uses a database named ``bulk``, and creates 25000 documents to save. Replace the ``<connection
172+
string>`` placeholder with a connection string for your Atlas deployment. For
143173
more information, see the :ref:`<java-get-started-connection-string>` section of
144-
this guide.
174+
this guide.
145175

146-
Object to Document Mapping
147-
~~~~~~~~~~~~~~~~~~~~~~~~~~
176+
Map Your Object to a Document
177+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
148178

149179
Mapping a class to a collection allows the Spring IoC container to store objects
150180
as MongoDB documents. You can use the ``@Document`` annotation to specify which
@@ -153,8 +183,8 @@ documents, see the `Mapping Annotation Overview
153183
<https://docs.spring.io/spring-data/mongodb/docs/current-SNAPSHOT/reference/html/#mapping-usage-annotations>`__
154184
section of the Spring Data MongoDB documentation.
155185

156-
The ``@Id`` annotation indicates that the ``id`` field maps to the ``_id`` field
157-
used as a unique identifier in MongoDB documents. You can choose any field of
186+
The ``@Id`` annotation in the following code indicates that the ``id`` field
187+
maps to the ``_id`` field which is used as a unique identifier in MongoDB documents. You can choose any field of
158188
any type, except arrays, to be the unique identifier. For more information, see
159189
the `How the _id field is handled in the mapping layer
160190
<https://docs.spring.io/spring-data/mongodb/reference/mongodb/mapping/mapping.html#mapping.conventions.id-field>`__
@@ -169,48 +199,46 @@ adding the following code to a ``Products.java`` file:
169199
:language: java
170200
:dedent:
171201

172-
You can add getters and setters for each field.
173-
174-
Implement a Bulk Write Method
175-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
176-
177-
The repository that stores your ``Products`` is implemented by two classes an
178-
interface, and an interface implementation. This allows you to create
179-
multiple product repositories for storing different products, while maintaining
180-
the same basic interface.
202+
The ``Products`` class includes a static method that generates an array of
203+
``Product`` objects. You may also define getters and setters for each field.
181204

182-
Create a generic repository interface with a bulk inserts method by adding the
183-
following code to a ``CustomProductsRepository.java`` file:
205+
Implement a Repository to Store Your Products
206+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
184207

185-
.. literalinclude:: /includes/integrations/spring-data-tutorial-code/main/java/CustomProductsRepository.java
186-
:start-after: // start-customproductsrepo
187-
:end-before: // end-customproductsrepo
188-
:language: java
189-
:dedent:
190-
191-
When you implement your products repository, you will need to reference the
208+
The ``ProductRepository`` will manage a collection of ``Products``.
209+
When you implement your ``ProductRepository``, you must reference the
192210
client creation methods defined in the ``MongoConfig`` class, which were
193211
annotated with ``@Bean``. By using the ``@Autowired`` annotation with the
194-
``mongoTemplate`` variable, the Spring container uses field injection to .
195-
196-
Create a class that implements and customizes the ``CustomProductsRepository``
197-
repository by adding the following code to a
198-
``CustomProductsRepositoryImpl.java`` file:
199-
200-
.. literalinclude:: /includes/integrations/spring-data-tutorial-code/main/java/CustomProductsRepositoryImpl.java
201-
:start-after: // start-customproductsrepoimpl
202-
:end-before: // end-customproductsrepoimpl
212+
``mongoTemplate`` variable together with a constructor that includes
213+
``mongoTemplate`` as an argument, the Spring container uses constructor
214+
injection to inject a ``mongoTemplate`` dependency. For more information about
215+
constructor injection, see the `Constructor-based Dependency Injection
216+
<https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html#beans-constructor-injection>`__
217+
section of the Spring Framework documentation.
218+
219+
Create the ``ProductRepository`` class that manages a collection of ``Products``
220+
by adding the following code to a ``ProductRepository.java`` file:
221+
222+
.. literalinclude:: /includes/integrations/spring-data-tutorial-code/main/java/ProductRepository.java
223+
:start-after: // start-productrepo
224+
:end-before: // end-productrepo
203225
:language: java
204226
:dedent:
205227

206-
The ``bulkInsertProducts()`` method uses unordered bulk inserts, which can improve performance by not guaranteeing the order of operations.
228+
The ``bulkInsertProducts()`` method uses unordered bulk inserts, which can
229+
improve performance by not guaranteeing the order of operations.
207230

208231
Perform a Bulk Operation
209232
~~~~~~~~~~~~~~~~~~~~~~~~
210233

211-
Create a main application class, trigger the bulk insert on startup:
234+
The main application class triggers the ``ProductRepository`` to generate the
235+
specified number of ``Products`` and save them to your MongoDB database. It uses
236+
the ``@Autowired`` annotation to inject a ``ProductRepository``, and implements logging.
237+
238+
Add the following code to a class of the same name as your project file, and add
239+
the following code:
212240

213-
.. literalinclude:: /includes/integrations/spring-data-tutorial-code/main/java/SpringDataBulkInsertApplication.java
241+
.. literalinclude:: /includes/integrations/spring-data-tutorial-code/main/java/MyProjectName.java
214242
:start-after: // start-application
215243
:end-before: // end-application
216244
:language: java
@@ -219,7 +247,11 @@ Create a main application class, trigger the bulk insert on startup:
219247
Conclusion
220248
----------
221249

222-
Implementing bulk writes in Spring Boot with MongoDB significantly improves performance by minimizing database round trips. By following the steps in this tutorial, you can efficiently manage batch data operations in your applications.
250+
Spring Data MongoDB provides a high-level abstraction for working with MongoDB.
251+
It can simplify application architecture by supporting automatic dependency
252+
injection, which eliminates the need for manual client configuration and complex
253+
query handling. By reducing boilerplate code and supporting object-oriented data access, it can
254+
streamline data access and promote a clear separation of concerns.
223255

224256
More Resources
225257
--------------

0 commit comments

Comments
 (0)