Create Database
Create a database with the name is SpringDataMongoDBRepository. This database have a collection: Product collection.
/* Create SpringDataMongoDBRepository database */
use SpringDataMongoDBRepository
/* Create Product collection */
db.createCollection('product');
/* Dumping data for `product` collection */
db.getCollection('product').insertOne({
"name" : "Mobile 1",
"price" : 45.0,
"quantity" : 4.0,
"status" : true,
"date" : ISODate("2016-10-20T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa45711668"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 1"
},
"colors" : [
"red",
"green",
"blue"
]
});
db.getCollection('product').insertOne({
"name" : "Mobile 2",
"price" : 12.0,
"quantity" : 7.0,
"status" : true,
"date" : ISODate("2017-11-14T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa45711668"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 2"
},
"colors" : [
"yellow",
"green"
]
});
db.getCollection('product').insertOne({
"name" : "Mobile 3",
"price" : 28.0,
"quantity" : 8.0,
"status" : true,
"date" : ISODate("2017-11-20T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa45711668"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 3"
},
"colors" : [
"black",
"blue"
]
});
db.getCollection('product').insertOne({
"name" : "Laptop 1",
"price" : 39.0,
"quantity" : 12.0,
"status" : false,
"date" : ISODate("2017-12-26T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa45711669"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 1"
},
"colors" : [
"blue"
]
});
db.getCollection('product').insertOne({
"name" : "Laptop 2",
"price" : 86.0,
"quantity" : 23.0,
"status" : true,
"date" : ISODate("2017-03-11T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa45711669"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 1"
},
"colors" : [
"blue",
"yellow"
]
});
db.getCollection('product').insertOne({
"name" : "Tivi 1",
"price" : 90,
"quantity" : 7.0,
"status" : true,
"date" : ISODate("2017-06-26T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa4571166a"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 1"
},
"colors" : [
"blue",
"white",
"black"
]
});
db.getCollection('product').insertOne({
"name" : "Tivi 2",
"price" : 86.0,
"quantity" : 23.0,
"status" : false,
"date" : ISODate("2017-09-24T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa4571166a"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 3"
},
"colors" : [
"red",
"green"
]
});
Create Spring Boot Project
On the Spring Tool Suite, create a Spring Boot project
Enter Project Information:
- Name: SpringBootMongoDB
- Group: com.example.demo
- Artifact: SpringBootMongoDB
- Description: Learn Spring Boot MongoDB with Real Apps
- Package: com.example.demo
Select the technologies and libraries to be used:
- Spring Data MongoDB
- Spring Boot Devtools
Click Next button to show Project’s Information
Click Finish button to finish create Spring Boot project
Configure pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>SpringBootMongoDB</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBootMongoDB</name>
<description>Learn Spring Boot MongoDB with Real Apps</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Database Configuration
Open application.properties file in src/main/resources folder and add configurations connect to database as below:
spring.data.mongodb.database=SpringDataMongoDBRepository
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost
Entities Class
Create new package named com.example.demo.entities. In this package, create new Java classes as below:
Brand Class
In com.example.demo.entities package, create new class named Brand.java as below:
package com.example.demo.entities;
public class Brand {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Brand(String id, String name) {
this.id = id;
this.name = name;
}
public Brand() {
}
}
Product Class
In com.example.demo.entities package, create new class named Product.java as below:
package com.example.demo.entities;
import java.util.Date;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "product")
public class Product {
@Id
private String id;
private String name;
private double price;
private int quantity;
private boolean status;
private Date date;
private String categoryId;
private Brand brand;
private List<String> colors;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public Brand getBrand() {
return brand;
}
public void setBrand(Brand brand) {
this.brand = brand;
}
public List<String> getColors() {
return colors;
}
public void setColors(List<String> colors) {
this.colors = colors;
}
}
ProductRepository Interface
Create new package named com.example.demo.repositories. In this package, create new interface named ProductRepository.java implement from CrudRepository interface of Spring Framework as below:
package com.example.demo.repositories;
import java.util.List;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.data.domain.Pageable;
import com.example.demo.entities.Product;
@Repository("productRepository")
public interface ProductRepository extends CrudRepository<Product, String> {
@Query("{}")
public List<Product> limit1(Pageable pageable);
@Query("{status: ?0}")
public List<Product> limit2(boolean status, Pageable pageable);
}
ProductService Interface
Create new package named com.example.demo.services. In this package create new interface named ProductService.java as below:
package com.example.demo.services;
import java.util.List;
import org.springframework.data.domain.Pageable;
import com.example.demo.entities.Product;
public interface ProductService {
public List<Product> limit1(Pageable pageable);
public List<Product> limit2(boolean status, Pageable pageable);
}
ProductServiceImpl Class
In com.example.demo.services package, create new java class named ProductServiceImpl.java implement from ProductService interface
package com.example.demo.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.example.demo.entities.Product;
import com.example.demo.repositories.ProductRepository;
@Service("productService")
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductRepository productRepository;
@Override
public List<Product> limit1(Pageable pageable) {
return productRepository.limit1(pageable);
}
@Override
public List<Product> limit2(boolean status, Pageable pageable) {
return productRepository.limit2(status, pageable);
}
}
Configuration Class
Create new package named com.example.demo.configurations, create new Java class named MongoDBConfigurations.java as below:
package com.example.demo.configurations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.example.demo.services.ProductService;
import com.example.demo.services.ProductServiceImpl;
@Configuration
@EnableTransactionManagement
@EnableMongoRepositories(basePackages = { "com.example.demo.repositories" })
@ComponentScan("com.example.demo")
@PropertySource("classpath:application.properties")
public class MongoDBConfigurations {
@Autowired
private MongoDatabaseFactory mongoDatabaseFactory;
@Autowired
private MongoMappingContext mongoMappingContext;
@Bean
public MappingMongoConverter mappingMongoConverter() {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDatabaseFactory);
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
converter.setTypeMapper(new DefaultMongoTypeMapper(null));
return converter;
}
@Bean
public ProductService productService() {
return new ProductServiceImpl();
}
}
Run Application
Create new package named com.example.demo.demo, create new Java class named Demo.java as below:
package com.example.demo.main;
import java.text.SimpleDateFormat;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.data.domain.PageRequest;
import com.example.demo.configurations.MongoDBConfigurations;
import com.example.demo.entities.Product;
import com.example.demo.services.ProductService;
public class Demo {
public static void main(String[] args) {
try {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(MongoDBConfigurations.class);
ProductService productService = context.getBean(ProductService.class);
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
System.out.println("Find 2 Newest Products");
for (Product product : productService.limit1(PageRequest.of(0, 2))) {
System.out.println("Id: " + product.getId());
System.out.println("Name: " + product.getName());
System.out.println("Price: " + product.getPrice());
System.out.println("Quantity: " + product.getQuantity());
System.out.println("Date: " + formatter.format(product.getDate()));
System.out.println("Status: " + product.isStatus());
System.out.println("Brand Info");
System.out.println("\tBrand Id: " + product.getBrand().getId());
System.out.println("\tBrand Name: " + product.getBrand().getName());
System.out.println("Colors:");
for (String color : product.getColors()) {
System.out.println("\t" + color);
}
System.out.println("================================");
}
System.out.println("Find 2 Newest Products with status is true");
for (Product product : productService.limit2(true, PageRequest.of(0, 2))) {
System.out.println("Id: " + product.getId());
System.out.println("Name: " + product.getName());
System.out.println("Price: " + product.getPrice());
System.out.println("Quantity: " + product.getQuantity());
System.out.println("Date: " + formatter.format(product.getDate()));
System.out.println("Status: " + product.isStatus());
System.out.println("Brand Info");
System.out.println("\tBrand Id: " + product.getBrand().getId());
System.out.println("\tBrand Name: " + product.getBrand().getName());
System.out.println("Colors:");
for (String color : product.getColors()) {
System.out.println("\t" + color);
}
System.out.println("================================");
}
context.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
Project Structure
Output
Find 2 products with the biggest price
Id: 5a586149cfad614dc07d93bb
Name: Tivi 1
Price: 90.0
Quantity: 7
Date: 06/26/2017 07:00:00
Status: false
Brand Info
Brand Id: 5a586149cfad614dc07d93ba
Brand Name: brand 1
Colors:
blue
white
black
================================
Id: 5a586149cfad614dc07d93b9
Name: Laptop 2
Price: 86.0
Quantity: 23
Date: 03/11/2017 07:00:00
Status: true
Brand Info
Brand Id: 5a586149cfad614dc07d93b8
Brand Name: brand 1
Colors:
blue
yellow
================================