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').insert({
"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').insert({
"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').insert({
"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').insert({
"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').insert({
"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').insert({
"name" : "Tivi 1",
"price" : 22.0,
"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').insert({
"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"
]
});
Java Libraries
Copy JAR files which are listed below:
antlr-2.7.7.jar
aopalliance-1.0.jar
aspectjrt-1.8.9.jar
aspectjweaver-1.8.9.jar
cglib-2.2.2.jar
com.springsource.org.apache.commons.logging-1.1.1.jar
com.springsource.org.apache.log4j-1.2.15.jar
commons-dbcp2-2.1.1.jar
commons-logging-1.1.3.jar
commons-pool2-2.4.2.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.2.Final.jar
hibernate-core-4.2.5.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.15.0-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
jcl-over-slf4j-1.7.1.jar
jmxtools-1.2.1.jar
mongo-java-driver-3.6.0.jar
slf4j-api-1.7.1.jar
slf4j-simple-1.7.25.jar
spring-aop-4.2.0.RELEASE.jar
spring-aspects-4.3.3.RELEASE.jar
spring-beans-4.2.0.RELEASE.jar
spring-context-4.2.0.RELEASE.jar
spring-core-4.2.0.RELEASE.jar
spring-data-commons-1.12.5.RELEASE.jar
spring-data-mongodb-1.9.5.RELEASE.jar
spring-expression-4.2.0.RELEASE.jar
spring-jdbc-4.2.0.RELEASE.jar
spring-jms-4.2.0.RELEASE.jar
spring-jmx-2.0.8.jar
spring-orm-4.2.0.RELEASE.jar
spring-oxm-4.2.0.RELEASE.jar
spring-tx-4.2.0.RELEASE.jar
Project Structure
Entities Class
Create entities classes: Product.java and Brand.java, to represent the above table
Brand.java
package 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.java
package 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;
}
}
Spring Data MongoDB Configuration File
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<context:component-scan base-package="demo.*" />
<mongo:mongo id="mongo" host="localhost" port="27017" />
<mongo:db-factory id="mongoDbFactory" dbname="SpringDataMongoDBRepository"
mongo-ref="mongo" />
<bean id="mappingContext"
class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />
<bean id="defaultMongoTypeMapper"
class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
<constructor-arg name="typeKey">
<null />
</constructor-arg>
</bean>
<bean id="mappingMongoConverter"
class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
<constructor-arg name="mappingContext" ref="mappingContext" />
<property name="typeMapper" ref="defaultMongoTypeMapper" />
</bean>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
<constructor-arg name="mongoConverter" ref="mappingMongoConverter" />
</bean>
<mongo:repositories base-package="demo.repositories"></mongo:repositories>
</beans>
ProductRepository Interface
The ProductRepository interface extends from CrudRepository interface of Spring Data MongoDB that provides CRUD operations for an entity.
package demo.repositories;
import org.springframework.stereotype.Repository;
import org.springframework.data.repository.CrudRepository;
import demo.entities.Product;
@Repository("productRepository")
public interface ProductRepository extends CrudRepository<Product, String> {
}
Run It
package demo.main;
import java.text.SimpleDateFormat;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import demo.entities.Product;
import demo.repositories.ProductRepository;
public class Main {
public static void main(String[] args) {
try {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
ProductRepository productRepository = (ProductRepository) applicationContext.getBean("productRepository");
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
for (Product product : productRepository.findAll()) {
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("================================");
}
applicationContext.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
Output
Id: 5a586149cfad614dc07d93b1
Name: Mobile 1
Price: 45.0
Quantity: 4
Date: 10/20/2016 07:00:00
Status: true
Brand Info
Brand Id: 5a586149cfad614dc07d93b0
Brand Name: brand 1
Colors:
red
green
blue
================================
Id: 5a586149cfad614dc07d93b3
Name: Mobile 2
Price: 12.0
Quantity: 7
Date: 11/14/2017 07:00:00
Status: true
Brand Info
Brand Id: 5a586149cfad614dc07d93b2
Brand Name: brand 2
Colors:
yellow
green
================================
Id: 5a586149cfad614dc07d93b5
Name: Mobile 3
Price: 28.0
Quantity: 8
Date: 11/20/2017 07:00:00
Status: true
Brand Info
Brand Id: 5a586149cfad614dc07d93b4
Brand Name: brand 3
Colors:
black
blue
================================
Id: 5a586149cfad614dc07d93b7
Name: Laptop 1
Price: 39.0
Quantity: 12
Date: 12/26/2017 07:00:00
Status: false
Brand Info
Brand Id: 5a586149cfad614dc07d93b6
Brand Name: brand 1
Colors:
blue
================================
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
================================
Id: 5a586149cfad614dc07d93bb
Name: Tivi 1
Price: 22.0
Quantity: 7
Date: 06/26/2017 07:00:00
Status: true
Brand Info
Brand Id: 5a586149cfad614dc07d93ba
Brand Name: brand 1
Colors:
blue
white
black
================================
Id: 5a586149cfad614dc07d93bd
Name: Tivi 2
Price: 86.0
Quantity: 23
Date: 09/24/2017 07:00:00
Status: false
Brand Info
Brand Id: 5a586149cfad614dc07d93bc
Brand Name: brand 3
Colors:
red
green
================================