Spring Boot Integration with mongoDB
Maven Dependency Add dependency for mongodb. Use embed mongodb instance in this project
1 2 3 4 5 6 7 8 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-data-mongodb</artifactId > </dependency > <dependency > <groupId > de.flapdoodle.embed</groupId > <artifactId > de.flapdoodle.embed.mongo</artifactId > </dependency >
MongoDB Integration MongoDB integration is very similar to MySQL integration. we add annotaiton to entity class and then create repository class to interact with the data store.
When embed mongodb dependency is included in POM file, you dont need to configure MongoDB connection info
If you don’t want to use an embeded mongodb server, you can use an actual server or a mongodb docker container. To run a mongodb container:
1 2 docker pull mongo docker run -d -p 27017-27019:27017-27019 --rm --name mongodb mongo
In the project, remove the embeded mongodb dependency, and then add the following to configuration files. You can specify the database to use here.
To connect to local MongoDB instance without username and password
1 spring.data.mongodb.uri =mongodb://127.0.0.1:27017/test
To connect local MongoDB instance with username and password
1 spring.data.mongodb.uri =mongodb://myusername:mypassword@localhost:27017/test?authSource=admin
There are two main ways to work with MongoDB, MongoTemplate ad the Repository support.
Entity 1 2 3 4 5 6 7 8 9 10 11 @Document(collection = "product") @Data @Builder public class Product { @Id private String id; private String name; private String category; private double price; private Date created; }
@Document annotation is optional. It tells spring this class maps to MongoDB document. use @Id
annnotation to map the id field.
MongoTemplate MongoTemplate provides rich methods to interact with MongoDB.
To use MongoTemplate just autowire MongoTemplate bean. Spring automatically creates MongoTemplate bean for you when you configure a MongoDB database.
1 2 @Autowired private MongoTemplate mongoTemplate;
Then you can use mongoTemplate’s methods insert, update, query and delete documents
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 package com.example.demo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.data.mongodb.core.MongoTemplate;import java.util.Date;import java.util.List;import static org.springframework.data.mongodb.core.query.Criteria.where;import static org.springframework.data.mongodb.core.query.Query.query;import static org.springframework.data.mongodb.core.query.Update.update;@SpringBootApplication public class DemoApplication implements CommandLineRunner { public static void main (String[] args) { SpringApplication.run(DemoApplication.class, args); } @Autowired private MongoTemplate mongoTemplate; @Override public void run (String... args) throws Exception { List<Product> productList = List.of( Product.builder().name("iPhone" ).category("Electronic" ).price(1000.00 ).created(new Date ()).build(), Product.builder().name("Samsung TV" ).category("Electronic" ).price(300.00 ).created(new Date ()).build(), Product.builder().name("Pillow" ).category("Home" ).price(200.0 ).created(new Date ()).build() ); mongoTemplate.insertAll(productList); List<Product> productsFromMongo = mongoTemplate.findAll(Product.class); productsFromMongo.forEach(System.out::println); mongoTemplate.updateFirst(query(where("name" ).is("iPhone" )), update("price" , 1200 ), Product.class); Product p = mongoTemplate.findOne(query(where("name" ).is("iPhone" )), Product.class); System.out.println(p); mongoTemplate.remove(query(where("name" ).is("iPhone" )), Product.class); mongoTemplate.dropCollection(Product.class); } }
Repository To use MongoRepository, we need to add @EnableMongoRepositories
annotation to Spring Boot configuration.
1 2 3 4 5 @Configuration @SpringBootApplication public class SomeConfigurationClass { .... }
Repository class
1 2 3 public interface ProductRepository extends MongoRepository <Product, String> { List<Product> findByCategory (String category) ; }
Similar to JpaRepository interface, MongoRepository interface has methods to create, update, query and delete documents.
Repository demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 @SpringBootApplication @EnableMongoRepositories public class DemoApplication implements CommandLineRunner { public static void main (String[] args) { SpringApplication.run(DemoApplication.class, args); } @Autowired private ProductRepository productRepository; @Override public void run (String... args) throws Exception { Product iphone = Product.builder().name("iPhone" ).category("Electronic" ).price(1000.00 ).created(new Date ()).build(); Product samsungTV = Product.builder().name("Samsung TV" ).category("Electronic" ).price(300.00 ).created(new Date ()).build(); Product pillow = Product.builder().name("Pillow" ).category("Home" ).price(200.0 ).created(new Date ()).build(); List<Product> productList = List.of(iphone, samsungTV, pillow); productRepository.insert(productList); List<Product> electronics = productRepository.findByCategory("Electronic" ); System.out.println("----electronics----" ); electronics.forEach(System.out::println); Optional<Product> iphoneFromMongo = productRepository.findOne(Example.of(Product.builder().name("iPhone" ).build(), ExampleMatcher.matchingAny())); iphoneFromMongo.ifPresentOrElse(ip -> { ip.setPrice(1200 ); productRepository.save(ip); }, () -> { System.err.println("iPhone not found :-(" ); }); System.out.println("---findAll----" ); productRepository.findAll().forEach(System.out::println); productRepository.deleteAll(); } }
see https://github.com/xinghua24/SpringBootExamples/tree/master/data-mongodb for the source code.
Reference