From 5b9c3a9a785b2b3a101811d5b1d4b39a38b29881 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Tue, 20 May 2025 10:07:53 -0400 Subject: [PATCH 1/3] first draft --- snooty.toml | 1 + source/integrations.txt | 4 + .../integrations/spring-data-integration.txt | 325 ++++++++++++++++++ 3 files changed, 330 insertions(+) create mode 100644 source/integrations/spring-data-integration.txt diff --git a/snooty.toml b/snooty.toml index 779c5740d..d841f5e34 100644 --- a/snooty.toml +++ b/snooty.toml @@ -19,6 +19,7 @@ toc_landing_pages = [ "/api-documentation", "/security", "/security/auth", + "/integrations" ] sharedinclude_root = "https://raw.githubusercontent.com/10gen/docs-shared/main/" diff --git a/source/integrations.txt b/source/integrations.txt index af3ad44f1..a012fdcdc 100644 --- a/source/integrations.txt +++ b/source/integrations.txt @@ -18,6 +18,10 @@ Third-Party Integrations :depth: 2 :class: singlecol +.. toctree:: + + Tutorial: Spring Data Framework + Overview -------- diff --git a/source/integrations/spring-data-integration.txt b/source/integrations/spring-data-integration.txt new file mode 100644 index 000000000..4a7324744 --- /dev/null +++ b/source/integrations/spring-data-integration.txt @@ -0,0 +1,325 @@ +.. _java-flask-celery: +.. original URL: https://www.mongodb.com/developer/products/mongodb/python-flask-celery-newsletter/ + +=========================================== +Tutorial: Spring Data Framework Integration +=========================================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 3 + :class: singlecol + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :description: Build an application using the Spring Data Framework and the MongoDB Java driver. + :keywords: spring, tutorial, bulk insert, code example + +Overview +-------- + +In this tutorial, you can learn how to use `Spring Data +MongoDB `__ with the +{+driver-short+} to build a bulk write application. + +Spring Data MongoDB +~~~~~~~~~~~~~~~~~~~ + +Spring Data MongoDB is a third-party Java ORM for MongoDB. The Spring Data +project provides a familiar and consistent Spring-based programming model which +is enhanced by MongoDB-specific features and capabilities. Spring Data MongoDB +uses a POJO-centric model for interacting with collections and writing +repository-style data access layers. + +The Spring Data BulkOperations Interface +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +BulkOperations is an Spring Framework interface that contains a list of write +operations that can be applied to your database. They can be any combination of +the following {+driver-short+} operations: + +- ``insert`` +- ``updateOne`` +- ``updateMany`` +- ``replaceOne`` +- ``deleteOne`` +- ``deleteMany`` +- ``upsert`` + +A BulkOperation can be ordered or unordered. Ordered operations will be applied +sequentially and if an error is detected, will return with an error code. +Unordered operations will be applied in parallel, which means they can be +faster. However, you must check if there were errors during the operations. + +For more information, see the `BulkOperations +`__ page of the +Spring Framework API documentation and the :manual:`Bulk Write Operations +` page of the MongoDB server manual. + +Tutorial +-------- + +You can find the completed sample app for this tutorial in the +:github:`SpringDataBulkInsert sample project +` GitHub repository. + +.. note:: Imports Not specified + + The import statements required for the classes in the tutorial have not been included. See the GitHub repository for complete files. + +Prerequisites +~~~~~~~~~~~~~ + +Ensure you have the following components installed and set up before you start +this tutorial: + +- `Java 8 or later `__ +- A MongoDB Atlas cluster + To learn how to set up a cluster, see the :ref:`Getting Started + `__ guide for more information. +- `Spring Boot application setup `__ +- Maven for dependency management + +Add Dependencies +~~~~~~~~~~~~~~~~ + +Add the following dependencies to your ``pom.xml``: + +.. code-block:: xml + + + + org.springframework.boot + spring-boot-starter-data-mongodb + 4.4.0 + + +Ensure that you are using a Spring Data version that is compatible with the +{+driver-long+} and Java versions you are using. For compatibility specifications, see +the `Requirements +`__ page +of the Spring Data MongoDB documentation, and the :ref:`Compatibility +` page of this guide. + +MongoClient Configuration +~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``MongodConfig`` class contains the configuration for the ``MongoClient`` +that will allow the Spring Data framework to interact with the MongoDB server +and sets the template for data operations. + +This application uses ``@Configuration`` annotations for classes, ``@Bean`` +annotations for methods, and ``@Value`` annotations for parameter conversion. +These annotations allow the Spring IoC container to manage objects. For a +detailed explanation of these annotations, see the following sections of the +Spring Data framework guide: + +- ``@Configuration`` and ``@Bean`` annotations: `Java-based Container + Configuration + `__ +- ``@Value`` annotations: `Using @Value + `__ + +Create configuration and template classes to set up your MongoDB connection by adding the +following code to your application: + +.. code-block:: java + + @Configuration + public class MongoConfig { + @Value("${mongodb.uri}") + private String uri; + + @Value("${mongodb.database}") + private String databaseName; + + // Indicates whether you deployment is managed by Atlas + @Value("${mongodb.atlas}") + private boolean atlas; + + // Details for accessing credentials in your JVM trust store + // for non-Atlas deployments + @Value("${truststore.path}") + private String trustStorePath; + @Value("${truststore.pwd}") + private String trustStorePwd; + + @Bean + public MongoClient mongo() { + ConnectionString connectionString = new ConnectionString(uri); + MongoClientSettings mongoClientSettings = MongoClientSettings.builder() + .applyConnectionString(connectionString) + .applyToSslSettings(builder -> { + if (!atlas) { + // Use SSLContext if a trustStore has been provided + if (!trustStorePath.isEmpty()) { + SSLFactory sslFactory = SSLFactory.builder() + .withTrustMaterial(Paths.get(trustStorePath), trustStorePwd.toCharArray()) + .build(); + SSLContext sslContext = sslFactory.getSslContext(); + builder.context(sslContext); + builder.invalidHostNameAllowed(true); + } + } + builder.enabled(true); + }) + .build(); + return MongoClients.create(mongoClientSettings); + } + + @Bean + public MongoTemplate mongoTemplate() throws Exception { + return new MongoTemplate(mongo(), databaseName); + } + } + +Ensure that your connection string (``mongodb.database``) and +database name (``mongodb.database``) are set in your environment variables. For +more information, see the :ref:`` section of +this guide. + +For non-Atlas deployments, ensure your JVM trust store information is set in +your environment variables. For more information, see the :ref:`Configure the +JVM Trust Store ` of this guide. + +Object to Document Mapping +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Mapping a class to a collection allows the Spring IoC container to store objects +as MongoDB documents. You can use the ``@Document`` annotation to specify which +collection a class maps to. For more information about mapping objects to MongoDB +documents, see the `Mapping Annotation Overview +`__ +section of the Spring Data MongoDB documentation. + +Create your ``Product`` class and map it to your ``products`` collection by +adding the following code to your application: + +.. code-block:: java + + @Document("products") + public class Products { + + private static final Logger LOG = LoggerFactory + .getLogger(Products.class); + + // Indicates our default index + @Id + private String id; + + private String name; + private int qty; + private double price; + private Date available; + private Date unavailable; + private String skuId; + + // Getters and setters + } + +You can add getters and setters for each field. + +Implement a Bulk Write Method +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The repository that stores your Products is implemented by two classes: an +interface, and an interface implementation. This will allow you to create +multiple product repositories for storing different products, while maintaining +a basic interface. + +Create a generic repository interface with a bulk inserts method by adding the +following code to your application: + +.. code-block:: java + + public interface CustomProductsRepository { + void updateProductQuantity(String name, int newQty); + int bulkInsertProducts(int count); + } + +Create a class that implements and customizes the repository by adding the +following code to your application: + +.. code-block:: java + + @Component + public class CustomProductsRepositoryImpl implements CustomProductsRepository { + + private static final Logger LOG = LoggerFactory + .getLogger(CustomProductsRepository.class); + + @Autowired + MongoTemplate mongoTemplate; + + public int bulkInsertProducts(int count) { + + // For testing purposes, clear any existing data in your product collection + LOG.info("Dropping collection..."); + mongoTemplate.dropCollection(Products.class); + LOG.info("Dropped!"); + + Instant start = Instant.now(); + mongoTemplate.setWriteConcern(WriteConcern.W1.withJournal(true)); + + Products [] productList = Products.RandomProducts(count); + BulkOperations bulkInsertion = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, Products.class); + + for (int i=0; i products = Arrays.asList( + new Product("Product1", 10, 100.0), + new Product("Product2", 20, 200.0) + ); + productRepository.bulkInsert(products); + } + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + } + +Conclusion +---------- + +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. + +More Resources +-------------- + +For more information about the Spring Data Framework, see the +following resources: + +- `Spring Framework Documentation `__ +- `Spring Data for MongoDB reference `__ +- `Spring Data for MongoDB API documentation `__ + +For support or to contribute to the MongoDB Community, see the `MongoDB Developer Community `__. \ No newline at end of file From 62bc102c8d899148e351b2e87a5a23685844c475 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Tue, 27 May 2025 11:31:58 -0400 Subject: [PATCH 2/3] edits --- source/integrations/spring-data-integration.txt | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/source/integrations/spring-data-integration.txt b/source/integrations/spring-data-integration.txt index 4a7324744..0ea040681 100644 --- a/source/integrations/spring-data-integration.txt +++ b/source/integrations/spring-data-integration.txt @@ -38,9 +38,9 @@ repository-style data access layers. The Spring Data BulkOperations Interface ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -BulkOperations is an Spring Framework interface that contains a list of write +BulkOperations is an Spring Framework Data interface that contains a list of write operations that can be applied to your database. They can be any combination of -the following {+driver-short+} operations: +the following operations which map to similar {+driver-short+} operations: - ``insert`` - ``updateOne`` @@ -55,10 +55,13 @@ sequentially and if an error is detected, will return with an error code. Unordered operations will be applied in parallel, which means they can be faster. However, you must check if there were errors during the operations. -For more information, see the `BulkOperations -`__ page of the -Spring Framework API documentation and the :manual:`Bulk Write Operations -` page of the MongoDB server manual. +For more information about bulk operations, see the following resources: + +- `BulkOperations + `__ + in the Spring Framework API documentation +- :ref:`Bulk Write Operations ` in this guide +- :manual:`Bulk Write Operations ` in the MongoDB server manual. Tutorial -------- @@ -69,7 +72,7 @@ You can find the completed sample app for this tutorial in the .. note:: Imports Not specified - The import statements required for the classes in the tutorial have not been included. See the GitHub repository for complete files. + The import statements required for the classes in the tutorial have not been included. See the :github:`GitHub repository` for complete files. Prerequisites ~~~~~~~~~~~~~ From d857cda88137f3834c11202668132500c4c60a93 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Thu, 12 Jun 2025 13:58:43 -0400 Subject: [PATCH 3/3] use includes --- .../main/java/CustomProductsRepository.java | 8 + .../java/CustomProductsRepositoryImpl.java | 68 +++++ .../main/java/MongoConfig.java | 64 +++++ .../main/java/Products.java | 107 ++++++++ .../java/SpringDataBulkInsertApplication.java | 35 +++ .../main/resources/application.properties | 10 + .../spring-data-tutorial-code/pom.xml | 76 ++++++ .../integrations/spring-data-integration.txt | 232 ++++++------------ 8 files changed, 437 insertions(+), 163 deletions(-) create mode 100644 source/includes/integrations/spring-data-tutorial-code/main/java/CustomProductsRepository.java create mode 100644 source/includes/integrations/spring-data-tutorial-code/main/java/CustomProductsRepositoryImpl.java create mode 100644 source/includes/integrations/spring-data-tutorial-code/main/java/MongoConfig.java create mode 100644 source/includes/integrations/spring-data-tutorial-code/main/java/Products.java create mode 100644 source/includes/integrations/spring-data-tutorial-code/main/java/SpringDataBulkInsertApplication.java create mode 100644 source/includes/integrations/spring-data-tutorial-code/main/resources/application.properties create mode 100644 source/includes/integrations/spring-data-tutorial-code/pom.xml diff --git a/source/includes/integrations/spring-data-tutorial-code/main/java/CustomProductsRepository.java b/source/includes/integrations/spring-data-tutorial-code/main/java/CustomProductsRepository.java new file mode 100644 index 000000000..f788c267b --- /dev/null +++ b/source/includes/integrations/spring-data-tutorial-code/main/java/CustomProductsRepository.java @@ -0,0 +1,8 @@ +package com.mongodb.examples.springdatabulkinsert; + +// start-customproductsrepo +public interface CustomProductsRepository { + void updateProductQuantity(String name, int newQty) ; + int bulkInsertProducts(int count); +} +// end-customproductsrepo diff --git a/source/includes/integrations/spring-data-tutorial-code/main/java/CustomProductsRepositoryImpl.java b/source/includes/integrations/spring-data-tutorial-code/main/java/CustomProductsRepositoryImpl.java new file mode 100644 index 000000000..e9d92cbf1 --- /dev/null +++ b/source/includes/integrations/spring-data-tutorial-code/main/java/CustomProductsRepositoryImpl.java @@ -0,0 +1,68 @@ +package com.mongodb.examples.springdatabulkinsert; + +import com.mongodb.WriteConcern; +import com.mongodb.bulk.BulkWriteResult; +import com.mongodb.client.result.UpdateResult; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.mongodb.core.BulkOperations; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.stereotype.Component; + +import java.time.Duration; +import java.time.Instant; + +// start-customproductsrepoimpl +@Component +public class CustomProductsRepositoryImpl implements CustomProductsRepository { + + private static final Logger LOG = LoggerFactory + .getLogger(CustomProductsRepository.class); + + private final MongoTemplate mongoTemplate; + + @Autowired + public CustomProductsRepositoryImpl(MongoTemplate mongoTemplate){ + this.mongoTemplate = mongoTemplate; + } + + + public void updateProductQuantity(String name, int newQuantity) { + Query query = new Query(Criteria.where("name").is(name)); + Update update = new Update(); + update.set("quantity", newQuantity); + + UpdateResult result = mongoTemplate.updateFirst(query, update, Products.class); + + if(result == null) + LOG.error("No documents updated"); + else + LOG.info(result.getModifiedCount() + " document(s) updated.."); + } + + public int bulkInsertProducts(int count) { + + LOG.info("Dropping collection..."); + mongoTemplate.dropCollection(Products.class); + LOG.info("Dropped!"); + + Instant start = Instant.now(); + mongoTemplate.setWriteConcern(WriteConcern.W1.withJournal(true)); + + Products [] productList = Products.RandomProducts(count); + BulkOperations bulkInsertion = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, Products.class); + + for (int i=0; i { + if (!atlas) { + // Use SSLContext if a trustStore has been provided + if (!trustStorePath.isEmpty()) { + SSLFactory sslFactory = SSLFactory.builder() + .withTrustMaterial(Paths.get(trustStorePath), trustStorePwd.toCharArray()) + .build(); + SSLContext sslContext = sslFactory.getSslContext(); + builder.context(sslContext); + builder.invalidHostNameAllowed(true); + } + } + builder.enabled(true); + }) + .build(); + + + return MongoClients.create(mongoClientSettings); + } + + @Bean + public MongoTemplate mongoTemplate() throws Exception { + return new MongoTemplate(mongo(), databaseName); + } +} +// end-mongoconfig diff --git a/source/includes/integrations/spring-data-tutorial-code/main/java/Products.java b/source/includes/integrations/spring-data-tutorial-code/main/java/Products.java new file mode 100644 index 000000000..8165c98e7 --- /dev/null +++ b/source/includes/integrations/spring-data-tutorial-code/main/java/Products.java @@ -0,0 +1,107 @@ +package com.mongodb.examples.springdatabulkinsert; + +import net.datafaker.Faker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +import java.util.Date; +import java.util.Random; + +// start-products-class +@Document("products") +public class Products { + + private static final Logger LOG = LoggerFactory + .getLogger(Products.class); + + @Id + private String id; + private String name; + private int qty; + private double price; + private Date available; + private Date unavailable; + private String skuId; + + public Products(String name, int qty, double price, Date available, Date unavailable, String skuId) { + this.name = name; + this.qty = qty; + this.price = price; + this.available = available; + this.unavailable = unavailable; + this.skuId = skuId; + } + + public static Products [] RandomProducts( int count) { + + Faker faker = new Faker(); + Random rand = new Random(); + + Products [] retProds = new Products[count]; + for (int i=0; i +mongodb.atlas=1 + +truststore.path=/etc/ssl/truststore.jks +truststore.pwd=P4ssw0rd + +documentCount=25000 diff --git a/source/includes/integrations/spring-data-tutorial-code/pom.xml b/source/includes/integrations/spring-data-tutorial-code/pom.xml new file mode 100644 index 000000000..4b345e2ad --- /dev/null +++ b/source/includes/integrations/spring-data-tutorial-code/pom.xml @@ -0,0 +1,76 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.2.5 + + + com.mongodb.examples + SpringDataBulkInsert + SpringDataBulkInsert + SpringDataBulkInsert + + 17 + + + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + + + org.projectlombok + lombok + true + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + net.datafaker + datafaker + 2.4.3 + + + + + io.github.hakky54 + sslcontext-kickstart + 8.3.7 + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/source/integrations/spring-data-integration.txt b/source/integrations/spring-data-integration.txt index 0ea040681..0154867a2 100644 --- a/source/integrations/spring-data-integration.txt +++ b/source/integrations/spring-data-integration.txt @@ -1,5 +1,5 @@ -.. _java-flask-celery: -.. original URL: https://www.mongodb.com/developer/products/mongodb/python-flask-celery-newsletter/ +.. _java-spring-data: +.. original URL: https://www.mongodb.com/developer/languages/java/java-spring-bulk-writes/ =========================================== Tutorial: Spring Data Framework Integration @@ -30,10 +30,10 @@ Spring Data MongoDB ~~~~~~~~~~~~~~~~~~~ Spring Data MongoDB is a third-party Java ORM for MongoDB. The Spring Data -project provides a familiar and consistent Spring-based programming model which -is enhanced by MongoDB-specific features and capabilities. Spring Data MongoDB -uses a POJO-centric model for interacting with collections and writing -repository-style data access layers. +project provides a familiar and consistent Spring-based programming model while +enabling MongoDB-specific features and capabilities. Spring Data MongoDB uses a +POJO-centric model for interacting with collections and writing repository-style +data access layers. The Spring Data BulkOperations Interface ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -61,18 +61,18 @@ For more information about bulk operations, see the following resources: `__ in the Spring Framework API documentation - :ref:`Bulk Write Operations ` in this guide -- :manual:`Bulk Write Operations ` in the MongoDB server manual. +- :manual:`Bulk Write Operations ` in the MongoDB server manual Tutorial -------- You can find the completed sample app for this tutorial in the :github:`SpringDataBulkInsert sample project -` GitHub repository. +` GitHub repository. .. note:: Imports Not specified - The import statements required for the classes in the tutorial have not been included. See the :github:`GitHub repository` for complete files. + The import statements required for the classes in the tutorial have not been included. See the :github:`GitHub repository` for complete files. Prerequisites ~~~~~~~~~~~~~ @@ -90,7 +90,14 @@ this tutorial: Add Dependencies ~~~~~~~~~~~~~~~~ -Add the following dependencies to your ``pom.xml``: +Ensure that you use a Spring Data MongoDB version that is compatible with the +{+driver-long+} and Java versions you are using. For compatibility specifications, see +the `Requirements +`__ page +of the Spring Data MongoDB documentation, and the :ref:`Compatibility +` page of this guide. + +Add the dependency to your ``pom.xml``: .. code-block:: xml @@ -98,22 +105,17 @@ Add the following dependencies to your ``pom.xml``: org.springframework.boot spring-boot-starter-data-mongodb - 4.4.0 + // Add as necessary -Ensure that you are using a Spring Data version that is compatible with the -{+driver-long+} and Java versions you are using. For compatibility specifications, see -the `Requirements -`__ page -of the Spring Data MongoDB documentation, and the :ref:`Compatibility -` page of this guide. - MongoClient Configuration ~~~~~~~~~~~~~~~~~~~~~~~~~ The ``MongodConfig`` class contains the configuration for the ``MongoClient`` -that will allow the Spring Data framework to interact with the MongoDB server -and sets the template for data operations. +that will allow the Spring Data framework to interact with the MongoDB server, +and sets other configuration options. For more information about configuration +options, see the :ref:`Specify Connection Options ` +page of this guide. This application uses ``@Configuration`` annotations for classes, ``@Bean`` annotations for methods, and ``@Value`` annotations for parameter conversion. @@ -128,67 +130,19 @@ Spring Data framework guide: `__ Create configuration and template classes to set up your MongoDB connection by adding the -following code to your application: - -.. code-block:: java - - @Configuration - public class MongoConfig { - @Value("${mongodb.uri}") - private String uri; - - @Value("${mongodb.database}") - private String databaseName; - - // Indicates whether you deployment is managed by Atlas - @Value("${mongodb.atlas}") - private boolean atlas; - - // Details for accessing credentials in your JVM trust store - // for non-Atlas deployments - @Value("${truststore.path}") - private String trustStorePath; - @Value("${truststore.pwd}") - private String trustStorePwd; - - @Bean - public MongoClient mongo() { - ConnectionString connectionString = new ConnectionString(uri); - MongoClientSettings mongoClientSettings = MongoClientSettings.builder() - .applyConnectionString(connectionString) - .applyToSslSettings(builder -> { - if (!atlas) { - // Use SSLContext if a trustStore has been provided - if (!trustStorePath.isEmpty()) { - SSLFactory sslFactory = SSLFactory.builder() - .withTrustMaterial(Paths.get(trustStorePath), trustStorePwd.toCharArray()) - .build(); - SSLContext sslContext = sslFactory.getSslContext(); - builder.context(sslContext); - builder.invalidHostNameAllowed(true); - } - } - builder.enabled(true); - }) - .build(); - return MongoClients.create(mongoClientSettings); - } - - @Bean - public MongoTemplate mongoTemplate() throws Exception { - return new MongoTemplate(mongo(), databaseName); - } - } +following code to a ``MongoConfig.java`` file: + +.. literalinclude:: /includes/integrations/spring-data-tutorial-code/main/java/MongoConfig.java + :start-after: // start-mongoconfig + :end-before: // end-mongoconfig + :language: java + :dedent: Ensure that your connection string (``mongodb.database``) and database name (``mongodb.database``) are set in your environment variables. For more information, see the :ref:`` section of this guide. -For non-Atlas deployments, ensure your JVM trust store information is set in -your environment variables. For more information, see the :ref:`Configure the -JVM Trust Store ` of this guide. - Object to Document Mapping ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -199,116 +153,68 @@ documents, see the `Mapping Annotation Overview `__ section of the Spring Data MongoDB documentation. -Create your ``Product`` class and map it to your ``products`` collection by -adding the following code to your application: - -.. code-block:: java - - @Document("products") - public class Products { - - private static final Logger LOG = LoggerFactory - .getLogger(Products.class); - - // Indicates our default index - @Id - private String id; +The ``@Id`` annotation indicates that the ``id`` field maps to the ``_id`` field +used as a unique identifier in MongoDB documents. You can choose any field of +any type, except arrays, to be the unique identifier. For more information, see +the `How the _id field is handled in the mapping layer +`__ +section of the Spring Data MongoDB documentation. - private String name; - private int qty; - private double price; - private Date available; - private Date unavailable; - private String skuId; +Create your ``Products`` class and map it to your ``products`` collection by +adding the following code to a ``Products.java`` file: - // Getters and setters - } +.. literalinclude:: /includes/integrations/spring-data-tutorial-code/main/java/Products.java + :start-after: // start-products-class + :end-before: // end-products-class + :language: java + :dedent: You can add getters and setters for each field. Implement a Bulk Write Method ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The repository that stores your Products is implemented by two classes: an -interface, and an interface implementation. This will allow you to create +The repository that stores your ``Products`` is implemented by two classes an +interface, and an interface implementation. This allows you to create multiple product repositories for storing different products, while maintaining -a basic interface. +the same basic interface. Create a generic repository interface with a bulk inserts method by adding the -following code to your application: - -.. code-block:: java - - public interface CustomProductsRepository { - void updateProductQuantity(String name, int newQty); - int bulkInsertProducts(int count); - } - -Create a class that implements and customizes the repository by adding the -following code to your application: - -.. code-block:: java - - @Component - public class CustomProductsRepositoryImpl implements CustomProductsRepository { - - private static final Logger LOG = LoggerFactory - .getLogger(CustomProductsRepository.class); +following code to a ``CustomProductsRepository.java`` file: - @Autowired - MongoTemplate mongoTemplate; +.. literalinclude:: /includes/integrations/spring-data-tutorial-code/main/java/CustomProductsRepository.java + :start-after: // start-customproductsrepo + :end-before: // end-customproductsrepo + :language: java + :dedent: - public int bulkInsertProducts(int count) { +When you implement your products repository, you will need to reference the +client creation methods defined in the ``MongoConfig`` class, which were +annotated with ``@Bean``. By using the ``@Autowired`` annotation with the +``mongoTemplate`` variable, the Spring container uses field injection to . - // For testing purposes, clear any existing data in your product collection - LOG.info("Dropping collection..."); - mongoTemplate.dropCollection(Products.class); - LOG.info("Dropped!"); +Create a class that implements and customizes the ``CustomProductsRepository`` +repository by adding the following code to a +``CustomProductsRepositoryImpl.java`` file: - Instant start = Instant.now(); - mongoTemplate.setWriteConcern(WriteConcern.W1.withJournal(true)); +.. literalinclude:: /includes/integrations/spring-data-tutorial-code/main/java/CustomProductsRepositoryImpl.java + :start-after: // start-customproductsrepoimpl + :end-before: // end-customproductsrepoimpl + :language: java + :dedent: - Products [] productList = Products.RandomProducts(count); - BulkOperations bulkInsertion = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, Products.class); - - for (int i=0; i products = Arrays.asList( - new Product("Product1", 10, 100.0), - new Product("Product2", 20, 200.0) - ); - productRepository.bulkInsert(products); - } - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - } +.. literalinclude:: /includes/integrations/spring-data-tutorial-code/main/java/SpringDataBulkInsertApplication.java + :start-after: // start-application + :end-before: // end-application + :language: java + :dedent: Conclusion ----------