├── .gitignore
├── README.md
├── pom.xml
└── src
├── main
├── java
│ └── com
│ │ └── spring
│ │ └── mongo
│ │ └── demo
│ │ ├── SpringBootMongoDBApplication.java
│ │ ├── config
│ │ ├── CORSFilter.java
│ │ └── DatabaseConfiguration.java
│ │ ├── controller
│ │ ├── EmployeeController.java
│ │ ├── EmployeeQueryController.java
│ │ └── SuperHeroController.java
│ │ ├── model
│ │ ├── Employee.java
│ │ └── SuperHero.java
│ │ ├── repository
│ │ ├── EmployeeQueryDao.java
│ │ ├── EmployeeRepository.java
│ │ ├── SuperHeroRepository.java
│ │ └── impl
│ │ │ └── EmployeeQueryDaoImpl.java
│ │ ├── service
│ │ ├── EmployeeQueryService.java
│ │ ├── EmployeeService.java
│ │ ├── SuperHeroService.java
│ │ └── impl
│ │ │ ├── EmployeeQueryServiceImpl.java
│ │ │ ├── EmployeeServiceImpl.java
│ │ │ └── SuperHeroServiceImpl.java
│ │ └── utils
│ │ └── HelperUtil.java
└── resources
│ └── application.properties
└── test
└── java
└── com
└── spring
└── mongo
└── demo
└── SpringBootMongoDBApplicationTests.java
/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**
5 | !**/src/test/**
6 |
7 |
8 |
9 | /mvnw.bat
10 | /mvnw.cmd
11 | /mvnw
12 | /.mvn/
13 |
14 |
15 |
16 | ### STS ###
17 | .apt_generated
18 | .classpath
19 | .factorypath
20 | .project
21 | .settings
22 | .springBeans
23 | .sts4-cache
24 |
25 | ### IntelliJ IDEA ###
26 | .idea
27 | *.iws
28 | *.iml
29 | *.ipr
30 |
31 | ### NetBeans ###
32 | /nbproject/private/
33 | /nbbuild/
34 | /dist/
35 | /nbdist/
36 | /.nb-gradle/
37 | build/
38 |
39 | ### VS Code ###
40 | .vscode/
41 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # spring-boot-mongodb-crud
2 |
3 | This project explains CRUD (**C**reate, **R**ead, **U**pdate, **D**elete) operations using MongoTemplate and MongoRepository using spring boot and mongo DB.
4 | In this app we are using Spring Data JPA for built-in methods to do CRUD operations and Mongo queries using MongoTemplate.
5 | `@EnableMongoRepositories` annotation is used on main class to Enable Mongo related configuration, which will read properties from `application.properties` file.
6 |
7 |
8 |
9 | ## Prerequisites
10 | - Java
11 | - [Spring Boot](https://spring.io/projects/spring-boot)
12 | - [Maven](https://maven.apache.org/guides/index.html)
13 | - [Mongo DB](https://docs.mongodb.com/guides/)
14 | - [Lombok](https://objectcomputing.com/resources/publications/sett/january-2010-reducing-boilerplate-code-with-project-lombok)
15 |
16 |
17 | ## Tools
18 | - Eclipse or IntelliJ IDEA (or any preferred IDE) with embedded Gradle
19 | - Maven (version >= 3.6.0)
20 | - Postman (or any RESTful API testing tool)
21 |
22 |
23 |
24 |
25 |
26 | ### Build and Run application
27 | _GOTO >_ **~/absolute-path-to-directory/spring-boot-mongodb**
28 | and try below command in terminal
29 | > **```mvn spring-boot:run```** it will run application as spring boot application
30 |
31 | or
32 | > **```mvn clean install```** it will build application and create **jar** file under target directory
33 |
34 | Run jar file from below path with given command
35 | > **```java -jar ~/path-to-spring-boot-mongodb/target/spring-boot-mongodb-0.0.1-SNAPSHOT.jar```**
36 |
37 | Or
38 | > run main method from `SpringBootMongoDBApplication.java` as spring boot application.
39 |
40 |
41 | ||
42 | | --------- |
43 | | **_Note_** : In `SpringBootMongoDBApplication.java` class we have autowired both SuperHero and Employee repositories.
If there is no record present in DB for any one of that module class (Employee or SuperHero), static data is getting inserted in DB from `HelperUtil.java` class when we are starting the app for the first time.|
44 |
45 |
46 |
47 | ### Code Snippets
48 | 1. #### Maven Dependencies
49 | Need to add below dependencies to enable Mongo related config in **pom.xml**. Lombok's dependency is to get rid of boiler-plate code.
50 | ```
51 |
52 | org.springframework.boot
53 | spring-boot-starter-data-mongodb
54 |
55 |
56 |
57 | org.projectlombok
58 | lombok
59 | true
60 |
61 | ```
62 |
63 |
64 | 2. #### Properties file
65 | Reading Mongo DB related properties from **application.properties** file and configuring Mongo connection factory for mongoDB.
66 |
67 | **src/main/resources/application.properties**
68 | ```
69 | spring.data.mongodb.host=localhost
70 | spring.data.mongodb.port=27017
71 | spring.data.mongodb.database=spring_boot_mongo_app
72 | spring.jackson.default-property-inclusion=NON_NULL
73 | #logging.level.ROOT=DEBUG
74 | ```
75 |
76 |
77 | 3. #### Model class
78 | Below are the model classes which we will store in MongoDB and perform CRUD operations.
79 | **com.spring.mongo.demo.model.SuperHero.java**
80 | ```
81 | @Data
82 | @AllArgsConstructor
83 | @NoArgsConstructor
84 | @Builder
85 | @Document(collection = "super_hero")
86 | public class SuperHero implements Serializable {
87 |
88 | @Id
89 | private String id;
90 |
91 | private String name;
92 | private String superName;
93 | private String profession;
94 | private int age;
95 | private boolean canFly;
96 |
97 | // Constructor, Getter and Setter
98 | }
99 | ```
100 | **com.spring.mongo.demo.model.Employee.java**
101 | ```
102 | @Data
103 | @AllArgsConstructor
104 | @NoArgsConstructor
105 | @Builder
106 | public class Employee implements Serializable {
107 |
108 | @Id
109 | private String id;
110 |
111 | private int empId;
112 | private String firstName;
113 | private String lastName;
114 | private float salary;
115 |
116 | // Constructor, Getter and Setter
117 | }
118 | ```
119 |
120 |
121 | 4. #### CRUD operation for Super Heroes
122 |
123 | In **com.spring.mongo.demo.controller.SuperHeroController.java** class,
124 | we have exposed 5 endpoints for basic CRUD operations
125 | - GET All Super Heroes
126 | - GET by ID
127 | - POST to store Super Hero in DB
128 | - PUT to update Super Hero
129 | - DELETE by ID
130 |
131 | ```
132 | @RestController
133 | @RequestMapping("/super-hero")
134 | public class SuperHeroController {
135 |
136 | @GetMapping
137 | public ResponseEntity> findAll();
138 |
139 | @GetMapping("/{id}")
140 | public ResponseEntity> findById(@PathVariable String id);
141 |
142 | @PostMapping
143 | public ResponseEntity> save(@RequestBody SuperHero superHero);
144 |
145 | @PutMapping
146 | public ResponseEntity> update(@RequestBody SuperHero superHero);
147 |
148 | @DeleteMapping("/{id}")
149 | public ResponseEntity> delete(@PathVariable String id);
150 | }
151 | ```
152 |
153 | In **com.spring.mongo.demo.repository.SuperHeroRepository.java**, we are extending `MongoRepository` interface which enables CRUD related methods.
154 | ```
155 | public interface SuperHeroRepository extends MongoRepository {
156 | }
157 | ```
158 |
159 | In **com.spring.mongo.demo.service.impl.SuperHeroServiceImpl.java**, we are autowiring above interface using `@Autowired` annotation and doing CRUD operation.
160 |
161 |
162 |
163 | 5. #### JPA And Query operation for Employee
164 | In **com.spring.mongo.demo.controller.EmployeeController.java** class JPA related queries API Endpoints are placed.
165 | In **com.spring.mongo.demo.controller.EmployeeQueryController.java** class Mongo queries API Endpoints are placed.
166 |
167 |
168 |
169 |
170 | ### API Endpoints
171 |
172 | - #### Super Hero CRUD Operations
173 | > **GET Mapping** http://localhost:8080/super-hero - Get all Super Heroes
174 |
175 | > **GET Mapping** http://localhost:8080/super-hero/5f380dece02f053eff29b986 - Get Super Hero by ID
176 |
177 | > **POST Mapping** http://localhost:8080/super-hero - Add new Super Hero in DB
178 |
179 | Request Body
180 | ```
181 | {
182 | "name": "Tony",
183 | "superName": "Iron Man",
184 | "profession": "Business",
185 | "age": 50,
186 | "canFly": true
187 | }
188 | ```
189 |
190 | > **PUT Mapping** http://localhost:8080/super-hero - Update existing Super Hero for given ID
191 |
192 | Request Body
193 | ```
194 | {
195 | "id": "5f380dece02f053eff29b986"
196 | "name": "Tony",
197 | "superName": "Iron Man",
198 | "profession": "Business",
199 | "age": 50,
200 | "canFly": true
201 | }
202 | ```
203 |
204 | > **DELETE Mapping** http://localhost:8080/super-hero/5f380dece02f053eff29b986 - Delete Super Hero by ID
205 |
206 | - #### Employee Get Operations using JPA
207 | > **GET Mapping** http://localhost:8080/employee-jpa - Get all Employees
208 |
209 | > **GET Mapping** http://localhost:8080/employee-jpa/5f380dece02f053eff29b986 - Get Employee by ID
210 |
211 | > **GET Mapping** http://localhost:8080/employee-jpa/firstName/Rahul - Get All Employees with firstname as Rahul
212 |
213 | > **GET Mapping** http://localhost:8080/employee-jpa/one-by-firstName/Rahul - Get **ONE** Employee with firstname as Rahul
214 |
215 | > **GET Mapping** http://localhost:8080/employee-jpa/firstName-like/Rahul - Get All Employees which contains Rahul in their firstname
216 |
217 | > **GET Mapping** http://localhost:8080/employee-jpa/one-by-lastName/Ghadage - Get **ONE** Employee with lastname as Ghadage
218 |
219 | > **GET Mapping** http://localhost:8080/employee-jpa/salary-greater-than/10000 - Get All Employees whose salary is grater than 1000
220 |
221 | > **POST Mapping** http://localhost:8080/employee-jpa/get-by-condition - Get All Employees with multiple condition
222 |
223 | Request Body
224 | ```
225 | {
226 | "id": "5f380dece02f053eff29b986"
227 | "empId": "1",
228 | "firstName": "Rahul",
229 | "lastName": "Khan",
230 | "salary": 5000
231 | }
232 | ```
233 |
234 | - #### Employee Get Operations using Queries
235 | > **GET Mapping** http://localhost:8080/employee-query - Get all Employees
236 |
237 | > **GET Mapping** http://localhost:8080/employee-query/firstName/Rahul - Get All Employees with firstname as Rahul
238 |
239 | > **GET Mapping** http://localhost:8080/employee-query/one-by-firstName/Rahul - Get **ONE** Employee with firstname as Rahul
240 |
241 | > **GET Mapping** http://localhost:8080/employee-query/firstName-like/Rahul - Get All Employees which contains Rahul in their firstname
242 |
243 | > **GET Mapping** http://localhost:8080/employee-query/one-by-lastName/Ghadage - Get **ONE** Employee with lastname as Ghadage
244 |
245 | > **GET Mapping** http://localhost:8080/employee-query/salary-greater-than/10000 - Get All Employees whose salary is grater than 1000
246 |
247 | > **POST Mapping** http://localhost:8080/employee-query/get-by-condition - Get All Employees with multiple condition
248 |
249 | Request Body
250 | ```
251 | {
252 | "id": "5f380dece02f053eff29b986"
253 | "empId": "1",
254 | "firstName": "Rahul",
255 | "lastName": "Khan",
256 | "salary": 5000
257 | }
258 | ```
259 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | org.springframework.boot
8 | spring-boot-starter-parent
9 | 2.3.2.RELEASE
10 |
11 |
12 | com.spring.mongo.demo
13 | spring-boot-mongodb
14 | 0.0.1-SNAPSHOT
15 | spring-boot-mongodb
16 | Demo project for spring-boot-mongodb
17 |
18 |
19 | 1.8
20 |
21 |
22 |
23 |
24 |
25 | org.springframework.boot
26 | spring-boot-starter-web
27 |
28 |
29 |
30 | org.springframework.boot
31 | spring-boot-starter-data-mongodb
32 |
33 |
34 |
35 | org.springframework.boot
36 | spring-boot-devtools
37 | runtime
38 | true
39 |
40 |
41 |
42 | org.projectlombok
43 | lombok
44 | true
45 |
46 |
47 |
48 |
49 | org.springframework.boot
50 | spring-boot-starter-test
51 | test
52 |
53 |
54 |
55 |
56 |
57 |
58 | org.springframework.boot
59 | spring-boot-maven-plugin
60 |
61 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/SpringBootMongoDBApplication.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo;
2 |
3 | import com.spring.mongo.demo.model.Employee;
4 | import com.spring.mongo.demo.model.SuperHero;
5 | import com.spring.mongo.demo.repository.EmployeeRepository;
6 | import com.spring.mongo.demo.repository.SuperHeroRepository;
7 | import com.spring.mongo.demo.utils.HelperUtil;
8 | import org.slf4j.Logger;
9 | import org.slf4j.LoggerFactory;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.boot.CommandLineRunner;
12 | import org.springframework.boot.SpringApplication;
13 | import org.springframework.boot.autoconfigure.SpringBootApplication;
14 | import org.springframework.context.annotation.Bean;
15 | import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
16 |
17 | import java.util.List;
18 |
19 |
20 | @SpringBootApplication
21 | @EnableMongoRepositories
22 | public class SpringBootMongoDBApplication {
23 |
24 | private final Logger LOGGER = LoggerFactory.getLogger(getClass());
25 |
26 | public static void main(String[] args) {
27 | SpringApplication.run(SpringBootMongoDBApplication.class, args);
28 | }
29 |
30 |
31 |
32 | @Autowired
33 | private EmployeeRepository employeeRepository;
34 |
35 | @Autowired
36 | private SuperHeroRepository superHeroRepository;
37 |
38 |
39 | @Bean
40 | CommandLineRunner runner() {
41 | return args -> {
42 | List employees = employeeRepository.findAll();
43 | if (employees.size() == 0) {
44 | LOGGER.info("******* Inserting Employees to DB *******");
45 | employeeRepository.saveAll(HelperUtil.employeeSupplier.get());
46 | } else {
47 | LOGGER.info("******* Employees stored in DB Size :: {}", employees.size());
48 | LOGGER.info("******* Employees stored in DB :: {}", employees);
49 | }
50 |
51 | List superHeroes = superHeroRepository.findAll();
52 | if (superHeroes.size() == 0) {
53 | LOGGER.info("******* Inserting Super heroes to DB *******");
54 | superHeroRepository.saveAll(HelperUtil.superHeroesSupplier.get());
55 | } else {
56 | LOGGER.info("******* Super heroes stored in DB Size :: {}", superHeroes.size());
57 | LOGGER.info("******* Super heroes stored in DB :: {}", superHeroes);
58 | }
59 | };
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/config/CORSFilter.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo.config;
2 |
3 | import java.io.IOException;
4 |
5 | import javax.servlet.Filter;
6 | import javax.servlet.FilterChain;
7 | import javax.servlet.FilterConfig;
8 | import javax.servlet.ServletException;
9 | import javax.servlet.ServletRequest;
10 | import javax.servlet.ServletResponse;
11 | import javax.servlet.http.HttpServletResponse;
12 |
13 | import org.springframework.stereotype.Component;
14 |
15 | @Component
16 | public class CORSFilter implements Filter {
17 |
18 |
19 | @Override
20 | public void init(FilterConfig filterConfig) throws ServletException {
21 |
22 | }
23 |
24 | @Override
25 | public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
26 | HttpServletResponse response = (HttpServletResponse) servletResponse;
27 | response.setHeader("Access-Control-Allow-Origin", "*");
28 | response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
29 | response.setHeader("Access-Control-Max-Age", "3600");
30 | response.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept");
31 | response.setHeader("Access-Control-Expose-Headers", "Location");
32 | filterChain.doFilter(servletRequest, servletResponse);
33 | }
34 |
35 | @Override
36 | public void destroy() {
37 |
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/config/DatabaseConfiguration.java:
--------------------------------------------------------------------------------
1 | //package com.spring.mongo.demo.config;
2 | //
3 | //
4 | //import com.mongodb.MongoClient;
5 | //import com.mongodb.MongoClientOptions;
6 | //import com.mongodb.MongoClientURI;
7 | //import org.slf4j.Logger;
8 | //import org.slf4j.LoggerFactory;
9 | //import org.springframework.beans.factory.annotation.Value;
10 | //import org.springframework.context.annotation.Bean;
11 | //import org.springframework.context.annotation.Configuration;
12 | //import org.springframework.context.annotation.Primary;
13 | //import org.springframework.data.mongodb.core.MongoTemplate;
14 | //import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
15 | //
16 | //@Configuration
17 | //public class DatabaseConfiguration {
18 | //
19 | // private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseConfiguration.class);
20 | //
21 | // @Value("${spring.data.mongodb.uri}")
22 | // private String mongoUri;
23 | //
24 | // @Value("${spring.data.mongodb.database}")
25 | // private String mongoDbName;
26 | //
27 | // @Primary
28 | // @Bean
29 | // public MongoTemplate mongoTemplate() {
30 | //
31 | // LOGGER.debug(" instantiating MongoDbFactory ");
32 | //
33 | // SimpleMongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient(), mongoDbName);
34 | //
35 | // return new MongoTemplate(mongoDbFactory);
36 | //
37 | // }
38 | //
39 | // @Primary
40 | // @Bean
41 | // public MongoClient mongoClient() {
42 | // return new MongoClient(mongoClientURI());
43 | // }
44 | //
45 | // @SuppressWarnings("deprecation")
46 | // @Primary
47 | // @Bean
48 | // public MongoClientURI mongoClientURI() {
49 | // LOGGER.debug(" creating connection with mongodb with uri [{}] ", mongoUri);
50 | // //return new MongoClientURI(mongoUri);
51 | //
52 | // MongoClientOptions.Builder options = MongoClientOptions.builder();
53 | // options.socketKeepAlive(true);
54 | // return new MongoClientURI(mongoUri, options);
55 | //
56 | // }
57 | //
58 | //}
59 | //
60 | //
61 | //
62 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/controller/EmployeeController.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo.controller;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.web.bind.annotation.*;
7 |
8 | import com.spring.mongo.demo.model.Employee;
9 | import com.spring.mongo.demo.service.EmployeeService;
10 |
11 | @RestController
12 | @RequestMapping("/employee-jpa")
13 | public class EmployeeController {
14 |
15 | @Autowired
16 | private EmployeeService employeeService;
17 |
18 | @GetMapping("/say")
19 | public String sayHello() {
20 | return "Hello Spring boot";
21 | }
22 |
23 | @GetMapping
24 | public List getAll() {
25 | return employeeService.getAll();
26 | }
27 |
28 |
29 | @GetMapping("/{empId}")
30 | public Employee getEmployeeById(@PathVariable int empId ) {
31 | return employeeService.getEmployeeById(empId);
32 | }
33 |
34 | @GetMapping("/firstName/{firstName}")
35 | public List getEmployeeByName(@PathVariable String firstName ) {
36 | return employeeService.getEmployeeByFirstName(firstName);
37 | }
38 |
39 | // get employee by first name (equals())
40 | @GetMapping("/one-by-firstName/{firstName}")
41 | public Employee getOneEmployeeByFirstName(@PathVariable String firstName) {
42 | return employeeService.getOneEmployeeByFirstName(firstName);
43 | }
44 |
45 | // get employee by first name %LIKE%
46 | @GetMapping("/firstName-like/{firstName}")
47 | public List getEmployeeByFirstNameLike(@PathVariable String firstName) {
48 | return employeeService.getEmployeeByFirstNameLike(firstName);
49 | }
50 |
51 | @GetMapping("/one-by-lastName/{lastName}")
52 | public Employee getEmployeeBylName(@PathVariable String lastName) {
53 | return employeeService.getEmployeeByLastName(lastName);
54 | }
55 |
56 |
57 | @GetMapping("/salary-greater-than/{salary}")
58 | public List getEmployeeBySalaryGreaterThan(@PathVariable int salary) {
59 | return employeeService.getEmployeeBySalaryGreaterThan(salary);
60 | }
61 |
62 | @PostMapping("/get-by-condition")
63 | public List getEmployeeByCondition(@RequestBody Employee employee) {
64 | return employeeService.getEmployeeByCondition(employee);
65 | }
66 | }
67 |
68 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/controller/EmployeeQueryController.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo.controller;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.web.bind.annotation.*;
7 |
8 | import com.spring.mongo.demo.model.Employee;
9 | import com.spring.mongo.demo.service.EmployeeQueryService;
10 |
11 | @RestController
12 | @RequestMapping("/employee-query")
13 | public class EmployeeQueryController {
14 |
15 | @Autowired
16 | private EmployeeQueryService employeeQueryService;
17 |
18 | @GetMapping
19 | public List getAll() {
20 | return employeeQueryService.getAll();
21 | }
22 |
23 |
24 | // getAll employee by first name (equals())
25 | @GetMapping("/firstName/{firstName}")
26 | public List getEmployeeByFirstName(@PathVariable String firstName) {
27 | return employeeQueryService.getEmployeeByFirstName(firstName);
28 | }
29 |
30 |
31 | // getAll employee by first name (equals())
32 | @GetMapping("/one-by-firstName/{firstName}")
33 | public Employee getOneEmployeeByFirstName(@PathVariable String firstName) {
34 | return employeeQueryService.getOneEmployeeByFirstName(firstName);
35 | }
36 |
37 | // getAll employee by first name %LIKE%
38 | @GetMapping("/firstName-like/{firstName}")
39 | public List getEmployeeByFirstNameLike(@PathVariable String firstName) {
40 | return employeeQueryService.getEmployeeByFirstNameLike(firstName);
41 | }
42 |
43 |
44 | // getAll employee by last name (equals())
45 | @GetMapping("/one-by-lastName/{lastName}")
46 | public Employee getSingleEmployeeByLastName(@PathVariable String lastName) {
47 | return employeeQueryService.getSingleEmployeeByLastName(lastName);
48 | }
49 |
50 |
51 | @GetMapping("/salary-greater-than/{salary}")
52 | public List getEmployeeBySalaryGreaterThan(@PathVariable int salary) {
53 | return employeeQueryService.getEmployeeBySalaryGreaterThan(salary);
54 | }
55 |
56 |
57 | @PostMapping("/get-by-condition")
58 | public List getEmployeeByCondition(@RequestBody Employee employee) {
59 | return employeeQueryService.getEmployeeByCondition(employee);
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/controller/SuperHeroController.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo.controller;
2 |
3 |
4 | import com.spring.mongo.demo.model.SuperHero;
5 | import com.spring.mongo.demo.service.SuperHeroService;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.web.bind.annotation.*;
9 |
10 | import java.util.List;
11 |
12 | @RestController
13 | @RequestMapping("/super-hero")
14 | public class SuperHeroController {
15 |
16 | @Autowired
17 | private SuperHeroService superHeroService;
18 |
19 | @GetMapping
20 | public ResponseEntity> findAll() {
21 | List> list = superHeroService.findAll();
22 | return ResponseEntity.ok().body(list);
23 | }
24 |
25 |
26 | @GetMapping("/{id}")
27 | public ResponseEntity> findById(@PathVariable String id) {
28 | SuperHero superHero = superHeroService.findById(id);
29 | return ResponseEntity.ok().body(superHero);
30 | }
31 |
32 |
33 | @PostMapping
34 | public ResponseEntity> save(@RequestBody SuperHero superHero) {
35 | SuperHero savedSuperHero = superHeroService.save(superHero);
36 | return ResponseEntity.ok().body(savedSuperHero);
37 | }
38 |
39 |
40 | @PutMapping
41 | public ResponseEntity> update(@RequestBody SuperHero superHero) {
42 | SuperHero updatedSuperHero = superHeroService.update(superHero);
43 | return ResponseEntity.ok().body(updatedSuperHero);
44 | }
45 |
46 |
47 | @DeleteMapping("/{id}")
48 | public ResponseEntity> delete(@PathVariable String id) {
49 | superHeroService.delete(id);
50 | return ResponseEntity.ok().body("Deleted successfully...!");
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/model/Employee.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo.model;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Builder;
5 | import lombok.Data;
6 | import lombok.NoArgsConstructor;
7 | import org.springframework.data.annotation.Id;
8 |
9 | import java.io.Serializable;
10 |
11 | @Data
12 | @AllArgsConstructor
13 | @NoArgsConstructor
14 | @Builder
15 | public class Employee implements Serializable {
16 |
17 | @Id
18 | private String id;
19 |
20 | private int empId;
21 | private String firstName;
22 | private String lastName;
23 | private float salary;
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/model/SuperHero.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo.model;
2 |
3 | import lombok.Builder;
4 | import lombok.Data;
5 | import lombok.AllArgsConstructor;
6 | import lombok.NoArgsConstructor;
7 | import org.springframework.data.annotation.Id;
8 | import org.springframework.data.mongodb.core.mapping.Document;
9 |
10 | import java.io.Serializable;
11 |
12 | @Data
13 | @AllArgsConstructor
14 | @NoArgsConstructor
15 | @Builder
16 | @Document(collection = "super_hero")
17 | public class SuperHero implements Serializable {
18 |
19 | @Id
20 | private String id;
21 |
22 | private String name;
23 | private String superName;
24 | private String profession;
25 | private int age;
26 | private boolean canFly;
27 |
28 | // Constructor, Getter and Setter
29 | }
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/repository/EmployeeQueryDao.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo.repository;
2 |
3 | import java.util.List;
4 |
5 | import com.spring.mongo.demo.model.Employee;
6 |
7 | public interface EmployeeQueryDao {
8 |
9 | List getAll();
10 |
11 | List getEmployeeByFirstName(String firstName);
12 |
13 | Employee getSingleEmployeeByFirstName(String firstName);
14 |
15 | List getEmployeeByFirstNameLike(String firstName);
16 |
17 | Employee getSingleEmployeeByLastName(String lastName);
18 |
19 | List getEmployeeBySalaryGreaterThan(int salary);
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/repository/EmployeeRepository.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo.repository;
2 |
3 | import org.springframework.data.mongodb.repository.MongoRepository;
4 |
5 | import com.spring.mongo.demo.model.Employee;
6 |
7 | import java.util.List;
8 |
9 | public interface EmployeeRepository extends MongoRepository {
10 |
11 | Employee findByFirstName(String firstName);
12 |
13 | List findByFirstNameLike(String firstName);
14 |
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/repository/SuperHeroRepository.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo.repository;
2 |
3 | import com.spring.mongo.demo.model.SuperHero;
4 | import org.springframework.data.mongodb.repository.MongoRepository;
5 |
6 |
7 | public interface SuperHeroRepository extends MongoRepository {
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/repository/impl/EmployeeQueryDaoImpl.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo.repository.impl;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.data.domain.Sort;
8 | import org.springframework.data.mongodb.core.MongoTemplate;
9 | import org.springframework.data.mongodb.core.query.Criteria;
10 | import org.springframework.data.mongodb.core.query.Query;
11 | import org.springframework.stereotype.Repository;
12 |
13 | import com.spring.mongo.demo.model.Employee;
14 | import com.spring.mongo.demo.repository.EmployeeQueryDao;
15 |
16 |
17 | @Repository
18 | class EmployeeQueryDaoImpl implements EmployeeQueryDao {
19 |
20 |
21 | @Autowired
22 | private MongoTemplate mongoTemplate;
23 |
24 | @Override
25 | public List getAll() {
26 | System.out.println("Inside Employee Query DAO Impl's get()");
27 | return mongoTemplate.findAll(Employee.class);
28 | }
29 |
30 |
31 | @Override
32 | public List getEmployeeByFirstName(String firstName) {
33 |
34 | Query query = new Query();
35 | query.addCriteria(Criteria.where("firstName").is(firstName));
36 | return new ArrayList<>(mongoTemplate.find(query, Employee.class));
37 | }
38 |
39 |
40 | @Override
41 | public Employee getSingleEmployeeByFirstName(String name) {
42 |
43 | Query query = new Query();
44 | query.addCriteria(Criteria.where("firstName").is(name));
45 |
46 | return mongoTemplate.findOne(query, Employee.class);
47 | }
48 |
49 |
50 | // "firstName" --> database property (not related to java code)
51 | // select * from employee where lastName like %Gurung% limit 1 --> (case insensitive)
52 | @Override
53 | public List getEmployeeByFirstNameLike(String firstName) {
54 |
55 | Query query = new Query();
56 | query.addCriteria(Criteria.where("firstName").regex(firstName, "i"));
57 |
58 | return mongoTemplate.find(query, Employee.class);
59 | }
60 |
61 |
62 | @Override
63 | public Employee getSingleEmployeeByLastName(String lastName) {
64 |
65 | Query query = new Query();
66 | query.addCriteria(Criteria.where("lastName").regex(lastName, "i"));
67 |
68 | return mongoTemplate.findOne(query, Employee.class);
69 | }
70 |
71 |
72 |
73 |
74 | @Override
75 | public List getEmployeeBySalaryGreaterThan(int salary) {
76 |
77 | Query query = new Query();
78 | query.addCriteria(Criteria.where("salary").gt(salary));
79 | query.with(Sort.by(Sort.Direction.ASC, "firstName"));
80 | query.with(Sort.by(new Sort.Order(Sort.Direction.ASC, "firstName").ignoreCase()));
81 |
82 | return mongoTemplate.find(query, Employee.class);
83 | }
84 |
85 |
86 | }
87 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/service/EmployeeQueryService.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo.service;
2 |
3 | import java.util.List;
4 |
5 | import com.spring.mongo.demo.model.Employee;
6 |
7 | public interface EmployeeQueryService {
8 |
9 | List getAll();
10 |
11 | List getEmployeeByFirstName(String firstName);
12 |
13 | Employee getSingleEmployeeByLastName(String lastName);
14 |
15 | List getEmployeeByFirstNameLike(String firstName);
16 |
17 | Employee getOneEmployeeByFirstName(String firstName);
18 |
19 | List getEmployeeBySalaryGreaterThan(int salary);
20 |
21 | List getEmployeeByCondition(Employee employee);
22 |
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/service/EmployeeService.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo.service;
2 |
3 |
4 | import java.util.List;
5 |
6 | import com.spring.mongo.demo.model.Employee;
7 |
8 | public interface EmployeeService {
9 |
10 | List getAll();
11 |
12 | List getEmployeeByFirstName(String firstName);
13 |
14 | Employee getOneEmployeeByFirstName(String firstName);
15 |
16 | List getEmployeeByFirstNameLike(String firstName);
17 |
18 | Employee getEmployeeById(int empId);
19 |
20 | Employee getEmployeeByLastName(String lastName);
21 |
22 | List getEmployeeBySalaryGreaterThan(int salary);
23 |
24 | List getEmployeeByCondition(Employee employee);
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/service/SuperHeroService.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo.service;
2 |
3 | import com.spring.mongo.demo.model.SuperHero;
4 |
5 | import java.util.List;
6 |
7 | public interface SuperHeroService {
8 |
9 | List> findAll();
10 |
11 | SuperHero findById(String id);
12 |
13 | SuperHero save(SuperHero superHero);
14 |
15 | SuperHero update(SuperHero superHero);
16 |
17 | void delete(String id);
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/service/impl/EmployeeQueryServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo.service.impl;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Collections;
5 | import java.util.List;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.stereotype.Service;
9 |
10 | import com.spring.mongo.demo.model.Employee;
11 | import com.spring.mongo.demo.repository.EmployeeQueryDao;
12 | import com.spring.mongo.demo.service.EmployeeQueryService;
13 | import org.springframework.util.StringUtils;
14 |
15 | @Service
16 | public class EmployeeQueryServiceImpl implements EmployeeQueryService {
17 |
18 | @Autowired
19 | private EmployeeQueryDao employeeQueryDao;
20 |
21 | @Override
22 | public List getAll() {
23 | System.out.println("Inside Employee Query Service Impl");
24 | return employeeQueryDao.getAll();
25 | }
26 |
27 | @Override
28 | public List getEmployeeByFirstName(String firstName) {
29 |
30 | if (!StringUtils.isEmpty(firstName)) {
31 | return employeeQueryDao.getEmployeeByFirstName(firstName);
32 | }
33 |
34 | return null;
35 | }
36 |
37 |
38 | @Override
39 | public Employee getOneEmployeeByFirstName(String firstName) {
40 |
41 | if (!StringUtils.isEmpty(firstName)) {
42 | return employeeQueryDao.getSingleEmployeeByFirstName(firstName);
43 | }
44 |
45 | return null;
46 | }
47 | @Override
48 | public List getEmployeeByFirstNameLike(String firstName) {
49 |
50 | if (!StringUtils.isEmpty(firstName)) {
51 | return employeeQueryDao.getEmployeeByFirstNameLike(firstName);
52 | }
53 |
54 | return null;
55 | }
56 |
57 |
58 | @Override
59 | public Employee getSingleEmployeeByLastName(String lastName) {
60 |
61 | if (!StringUtils.isEmpty(lastName)) {
62 | return employeeQueryDao.getSingleEmployeeByLastName(lastName);
63 | }
64 | return Employee.builder().empId(0).firstName("Not Found").lastName("Please enter valid last name").salary(0f).build();
65 | }
66 |
67 | @Override
68 | public List getEmployeeBySalaryGreaterThan(int salary) {
69 |
70 | if (salary > 0) {
71 | return employeeQueryDao.getEmployeeBySalaryGreaterThan(salary);
72 | }
73 | return Collections.emptyList();
74 | }
75 |
76 | @Override
77 | public List getEmployeeByCondition(Employee employee) {
78 | List list = employeeQueryDao.getAll();
79 | List employees = new ArrayList<>();
80 |
81 | if (null != employee && (null != employee.getFirstName() || employee.getEmpId() > 0
82 | || null != employee.getLastName() || employee.getSalary() > 0)) {
83 |
84 | for (Employee emp : list) {
85 |
86 | if (null != employee.getFirstName() && employee.getEmpId() > 0 && null != employee.getLastName()
87 | && employee.getSalary() > 0) {
88 |
89 | if (emp.getEmpId() == employee.getEmpId()
90 | && emp.getFirstName().equalsIgnoreCase(employee.getFirstName())
91 | && emp.getLastName().equalsIgnoreCase(employee.getLastName())
92 | && emp.getSalary() == employee.getSalary()) {
93 | employees.add(emp);
94 |
95 | break;
96 | } else {
97 | continue;
98 | }
99 | }
100 | if (employee.getEmpId() == emp.getEmpId()) {
101 | employees.add(emp);
102 | continue;
103 | }
104 |
105 | // First name
106 | if (null != employee.getFirstName()) {
107 | if (emp.getFirstName().toLowerCase().contains(employee.getFirstName().toLowerCase())) {
108 | employees.add(emp);
109 | // Go back to first statement (nothing but for loop)
110 | continue;
111 | }
112 | }
113 |
114 | // Last name
115 | if (null != employee.getLastName()) {
116 | if (emp.getLastName().equalsIgnoreCase(employee.getLastName()))
117 | employees.add(emp);
118 | // Go back to first statement (nothing but for loop)
119 | continue;
120 | }
121 | // salary
122 | if (employee.getSalary() == emp.getSalary()) {
123 | employees.add(emp);
124 | }
125 | // ---------------------------------------------------------
126 | }
127 | // returning the list
128 | return employees;
129 | }
130 | // if below statements return false only then below list is returning
131 | // if (null != employee &&
132 | // (null != employee.getFirstName() || employee.getEmpId() > 0
133 | // || null != employee.getLastName() || employee.getSalary() > 0))
134 | return employees;
135 | }
136 |
137 | }
138 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/service/impl/EmployeeServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo.service.impl;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.stereotype.Service;
8 |
9 | import com.spring.mongo.demo.model.Employee;
10 | import com.spring.mongo.demo.repository.EmployeeRepository;
11 | import com.spring.mongo.demo.service.EmployeeService;
12 |
13 | @Service
14 | public class EmployeeServiceImpl implements EmployeeService {
15 |
16 |
17 | @Autowired
18 | private EmployeeRepository repository;
19 |
20 |
21 |
22 | @Override
23 | public List getAll() {
24 | return repository.findAll();
25 | }
26 |
27 | @Override
28 | public Employee getEmployeeByLastName(String lastName) {
29 |
30 | List employees = repository.findAll();
31 |
32 | for (Employee emp : employees) {
33 | if (emp.getLastName().equalsIgnoreCase(lastName))
34 | return emp;
35 | }
36 | return Employee.builder().empId(0).firstName("Not Found").lastName("Please enter valid id").salary(0f).build();
37 | }
38 |
39 | @Override
40 | public Employee getEmployeeById(int empId) {
41 | List employees = repository.findAll();
42 | for (Employee emp : employees) {
43 | if (empId == emp.getEmpId())
44 | return emp;
45 | }
46 | return Employee.builder().empId(0).firstName("Not Found").lastName("Please enter valid id").salary(0f).build();
47 | }
48 |
49 | @Override
50 | public List getEmployeeByFirstName(String firstName) {
51 | List employees = new ArrayList<>();
52 | List list = repository.findAll();
53 | for (Employee emp : list) {
54 | if (emp.getFirstName().equalsIgnoreCase(firstName))
55 | employees.add(emp);
56 | }
57 | return employees;
58 | }
59 |
60 | @Override
61 | public Employee getOneEmployeeByFirstName(String firstName) {
62 | return repository.findByFirstName(firstName);
63 | }
64 |
65 | @Override
66 | public List getEmployeeByFirstNameLike(String firstName) {
67 | return repository.findByFirstNameLike(firstName);
68 | }
69 |
70 | // @Override
71 | // public Employee getEmployeeByFirstName(Employee employee) {
72 | // List list = repository.findAll();
73 | // for (Employee emp : list) {
74 | // if (emp.getFirstName().equals(employee.getFirstName()))
75 | // return emp;
76 | // }
77 | // return Employee.builder().empId(0).firstName("Not Found").lastName("Please enter valid id").salary(0f).build();
78 | // }
79 | //
80 | // @Override
81 | // public List getEmployeeByFrName(Employee employee) {
82 | // List employees = new ArrayList<>();
83 | //
84 | // if (null != employee && null != employee.getFirstName()
85 | // && !(employee.getFirstName().equals(""))) {
86 | // List list = repository.findAll();
87 | //
88 | // for (Employee emp : list) {
89 | // if (emp.getFirstName().toLowerCase().contains(employee.getFirstName().toLowerCase())) {
90 | // employees.add(emp);
91 | // }
92 | // }
93 | // }
94 | // return employees;
95 | // }
96 |
97 | @Override
98 | public List getEmployeeBySalaryGreaterThan(int salary) {
99 | List employees = new ArrayList<>();
100 |
101 | if (salary > 0) {
102 | List list = repository.findAll();
103 |
104 | for (Employee emp : list) {
105 | if (emp.getSalary() > salary)
106 | employees.add(emp);
107 | }
108 | }
109 | return employees;
110 | }
111 |
112 |
113 |
114 |
115 | @Override
116 | public List getEmployeeByCondition(Employee employee) {
117 | List list = repository.findAll();
118 | List employees = new ArrayList<>();
119 |
120 | // This will return true if employee object is present(not null) any one of
121 | // property is not null OR greater than 0
122 | if (null != employee && (null != employee.getFirstName() || employee.getEmpId() > 0
123 | || null != employee.getLastName() || employee.getSalary() > 0)) {
124 |
125 | for (Employee emp : list) {
126 |
127 | // If all 4 properties are present then only this block will execute
128 | if (null != employee.getFirstName() && employee.getEmpId() > 0 && null != employee.getLastName()
129 | && employee.getSalary() > 0) {
130 |
131 | if (emp.getEmpId() == employee.getEmpId()
132 | && emp.getFirstName().equalsIgnoreCase(employee.getFirstName())
133 | && emp.getLastName().equalsIgnoreCase(employee.getLastName())
134 | && emp.getSalary() == employee.getSalary()) {
135 | employees.add(emp);
136 | // Break the for loop
137 | break;
138 | } else {
139 | // Go back to first statement
140 | continue;
141 | }
142 | }
143 |
144 | // if any one of above property is null or less than equals to 0 then below
145 | // block is executing
146 | // Emp Id
147 | if (employee.getEmpId() == emp.getEmpId()) {
148 | employees.add(emp);
149 | // Go back to first statement
150 | continue;
151 | }
152 |
153 | // First name
154 | if (null != employee.getFirstName()) {
155 | if (emp.getFirstName().toLowerCase().contains(employee.getFirstName().toLowerCase())) {
156 | employees.add(emp);
157 | // Go back to first statement
158 | continue;
159 | }
160 | }
161 |
162 | // Last name
163 | if (null != employee.getLastName()) {
164 | if (emp.getLastName().equalsIgnoreCase(employee.getLastName()))
165 | employees.add(emp);
166 | // Go back to first statement
167 | continue;
168 | }
169 | // salary
170 | if (employee.getSalary() == emp.getSalary()) {
171 | employees.add(emp);
172 | }
173 | // ---------------------------------------------------------
174 | }
175 | // returning the list
176 | return employees;
177 | }
178 | // if below statements return false only then below list is returning
179 | // if (null != employee &&
180 | // (null != employee.getFirstName() || employee.getEmpId() > 0
181 | // || null != employee.getLastName() || employee.getSalary() > 0))
182 | return employees;
183 | }
184 |
185 | }
186 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/service/impl/SuperHeroServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo.service.impl;
2 |
3 | import com.spring.mongo.demo.model.SuperHero;
4 | import com.spring.mongo.demo.repository.SuperHeroRepository;
5 | import com.spring.mongo.demo.service.SuperHeroService;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.stereotype.Service;
8 |
9 | import java.util.List;
10 |
11 | @Service
12 | public class SuperHeroServiceImpl implements SuperHeroService {
13 |
14 | @Autowired
15 | private SuperHeroRepository repository;
16 |
17 | @Override
18 | public List findAll() {
19 | return repository.findAll();
20 | }
21 |
22 | @Override
23 | public SuperHero findById(String id) {
24 | return repository.findById(id).orElse(new SuperHero());
25 | }
26 |
27 | @Override
28 | public SuperHero save(SuperHero superHero) {
29 | return repository.save(superHero);
30 | }
31 |
32 | @Override
33 | public SuperHero update(SuperHero superHero) {
34 | return repository.save(superHero);
35 | }
36 |
37 | @Override
38 | public void delete(String id) {
39 | repository.findById(id).ifPresent(superHero -> repository.delete(superHero));
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/com/spring/mongo/demo/utils/HelperUtil.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo.utils;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.function.Supplier;
6 |
7 | import com.spring.mongo.demo.model.Employee;
8 | import com.spring.mongo.demo.model.SuperHero;
9 |
10 | public class HelperUtil {
11 |
12 | private HelperUtil() {
13 | }
14 |
15 |
16 | public static Supplier> employeeSupplier = () ->
17 | Arrays.asList(
18 | Employee.builder().empId(1).firstName("Binay").lastName("Gurung").salary(3000.0f).build(),
19 | Employee.builder().empId(2).firstName("Rahul").lastName("Ghadage").salary(4000.0f).build(),
20 | Employee.builder().empId(3).firstName("Sunny").lastName("Deol").salary(5000.0f).build(),
21 | Employee.builder().empId(4).firstName("Salman").lastName("Khan").salary(6000.0f).build(),
22 | Employee.builder().empId(5).firstName("Aamir").lastName("Khan").salary(7000.0f).build(),
23 | Employee.builder().empId(6).firstName("Shahrukh").lastName("Khan").salary(8000.0f).build(),
24 | Employee.builder().empId(7).firstName("Ranbir").lastName("Kapoor").salary(9000.0f).build(),
25 | Employee.builder().empId(8).firstName("Ranveer").lastName("Singh").salary(10000.0f).build(),
26 | Employee.builder().empId(9).firstName("Akshay").lastName("Kumar").salary(11000.0f).build(),
27 | Employee.builder().empId(10).firstName("Ajay").lastName("Devgan").salary(12000.0f).build()
28 | );
29 |
30 |
31 |
32 | public static Supplier> superHeroesSupplier = () ->
33 | Arrays.asList(
34 | SuperHero.builder().name("Wade").superName("Deadpool").profession("Street fighter").age(28).canFly(false).build(),
35 | SuperHero.builder().name("Bruce").superName("Hulk").profession("Doctor").age(50).canFly(false).build(),
36 | SuperHero.builder().name("Steve").superName("Captain America").profession("Solder").age(120).canFly(false).build(),
37 | SuperHero.builder().name("Tony").superName("Iron Man").profession("Business man").age(45).canFly(true).build(),
38 | SuperHero.builder().name("Peter").superName("Spider Man").profession("Student").age(21).canFly(true).build()
39 | );
40 |
41 |
42 |
43 |
44 | // public static List getStaticStudent() {
45 | //
46 | //
47 | // //System.out.println(developer);
48 | //
49 | // List list = new ArrayList<>();
50 | //
51 | // list.add(new Student(1, "Binay", "Gurung", 490, 500));
52 | // list.add(new Student(2, "Rahul", "Ghadage", 400, 500));
53 | // list.add(new Student(3, "Sunny", "Deol", 450, 500));
54 | // list.add(new Student(4, "Salman", "Khan", 440, 500));
55 | // list.add(new Student(5, "Aamir", "Khan", 400, 500));
56 | // list.add(new Student(6, "Sanjay", "Dutt", 420, 500));
57 | // list.add(new Student(7, "Sharukh", "Khan", 300, 500));
58 | // list.add(new Student(8, "Ranbir", "Kapoor", 320, 500));
59 | // list.add(new Student(9, "Ranveer", "Singh", 250, 500));
60 | // list.add(new Student(10, "Akshay", "Kumar", 280, 500));
61 | // list.add(new Student(11, "Ajay", "Devgan", 340, 500));
62 | // list.add(new Student(12, "Kishore", "Kumar", 399, 500));
63 | // list.add(new Student(13, "Bobby", "Deol", 345, 500));
64 | // list.add(new Student(14, "Rishi", "Kapoor", 355, 500));
65 | // list.add(new Student(15, "Jhon", "Abraham", 407, 500));
66 | // list.add(new Student(16, "Sunil", "Shetty", 421, 500));
67 | // list.add(new Student(17, "Manoj", "Bajpaye", 422, 500));
68 | // list.add(new Student(18, "Sunil", "Grover", 308, 500));
69 | // list.add(new Student(19, "Jhonny", "Lever", 267, 500));
70 | // list.add(new Student(20, "Abhishek", "Bachhan", 380, 500));
71 | // list.add(new Student(21, "Nitesh", "Deshmuk", 434, 500));
72 | // list.add(new Student(22, "Akshay", "Khanna", 402, 500));
73 | // list.add(new Student(23, "Arjit", "Singh", 347, 500));
74 | // list.add(new Student(24, "Kumar", "Sanu", 254, 500));
75 | // list.add(new Student(25, "Abhijit", "Babu", 344, 500));
76 | //
77 | // return list;
78 | //
79 | // }
80 |
81 | }
82 |
--------------------------------------------------------------------------------
/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 |
2 | # developer name
3 | application.developer = aryan
4 |
5 | #spring.data.mongodb.uri= mongodb://192.168.0.105:27017/spring_boo_mongo_app
6 | #spring.data.mongodb.database= spring_boo_mongo_app
7 |
8 | spring.data.mongodb.host=localhost
9 | spring.data.mongodb.port=27017
10 | spring.data.mongodb.database=spring_boot_mongo_app
11 | spring.jackson.default-property-inclusion=NON_NULL
12 | #logging.level.ROOT=DEBUG
13 |
--------------------------------------------------------------------------------
/src/test/java/com/spring/mongo/demo/SpringBootMongoDBApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.spring.mongo.demo;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class SpringBootMongoDBApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------