Commit 4f0a2b49 authored by gkhan's avatar gkhan

MongoDb criteria, Aggregration & relationship POC code added

parent 0c8f5bbc
# springboot-mongodb-example
1) This is a springboot application with MongoDb examples
I)Basic CRUD oprations
II)Criteria examples like ( ByName, gt , lt)
III)@query examples with gt,lt,regex, fields & values example
IV)Aggregation examples
V)MongoDb Realtionship with Embedded docuements
Swagger Adding steps
1) Adding dependencies in pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
2)Adding configuration & enabling swagger in main class
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.nisum.springboot")).build();
}
@EnableSwagger2
3) adding below peoperty in application.properties file
spring.mvc.pathmatch.matching-strategy=ant-path-matcher
<?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"
<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.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.nisum</groupId>
<artifactId>springboot-mongodb</artifactId>
......@@ -36,6 +37,18 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
<build>
......
......@@ -2,12 +2,33 @@ package com.nisum.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
public class SpringbootMongodbApplication {
//http://localhost:8888/swagger-ui.html
//http://localhost:8888/v2/api-docs
public static void main(String[] args) {
SpringApplication.run(SpringbootMongodbApplication.class, args);
}
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.nisum.springboot")).build();
// This below code also working fine http://localhost:8888/swagger-ui.html
/*
* return new Docket(DocumentationType.SWAGGER_2) .select()
* .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build();
*/
}
}
package com.nisum.springboot;
public class SwaggerConfig {
}
package com.nisum.springboot.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.GroupOperation;
import org.springframework.data.mongodb.core.aggregation.MatchOperation;
import org.springframework.data.mongodb.core.aggregation.SortOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.nisum.springboot.dto.AgeCount;
import com.nisum.springboot.entity.Employee;
import com.nisum.springboot.entity.Product;
import com.nisum.springboot.service.EmployeeService;
@RestController
@RequestMapping("/employees")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@PostMapping
List<Employee> saveEmployees(@RequestBody List<Employee> employees){
return employeeService.saveEmployees(employees);
}
@GetMapping
List<Employee> getAllEmployees(){
return employeeService.getAllEmployees();
}
@GetMapping("/name/{name}")
List<Employee> getEmployeeName(@PathVariable String name){
return employeeService.findByName(name);
}
@GetMapping("/name/{name}/dept/{department}")
List<Employee> findByNameAndDept(@PathVariable String name , @PathVariable String department){
return employeeService.findByNameAndDept(name,department);
}
@GetMapping("/minage/{minage}/maxage/{maxage}")
List<Employee> getEmployeesAgeBetween(@PathVariable int minage, @PathVariable int maxage){
return employeeService.getEmployeesAgeBetween(minage, maxage);
}
@Autowired
private MongoTemplate mongoTemplate;
@GetMapping("/namewithquery/{name}")
List<Employee> getEmployeeNameWithQuery(@PathVariable String name){
Query query= new Query();
//query.addCriteria(Criteria.where("name").is(name));
query.addCriteria(Criteria.where("name").regex(name));
return mongoTemplate.find(query, Employee.class);
}
@GetMapping("/namewithqueryreg/{name}")
List<Employee> getEmployeeNamewithReg(@PathVariable String name){
Query query= new Query();
query.addCriteria(Criteria.where("name").regex(name));
return mongoTemplate.find(query, Employee.class);
}
@GetMapping("/aggregateexample/{age}")
List<Employee> findByAgeMatch(@PathVariable int age){
MatchOperation matchoperation=Aggregation.match(new Criteria("age").is(age));
SortOperation sortoperation=Aggregation.sort(Sort.by(Sort.Direction.DESC, "age"));
Aggregation aggregation=Aggregation.newAggregation(matchoperation, sortoperation);
AggregationResults<Employee> results=mongoTemplate.aggregate(aggregation, "employees", Employee.class);
//return mongoTemplate.find("", Employee.class);
return results.getMappedResults();
}
@GetMapping("/aggregategroupexample/{age}")
List<AgeCount> findByAgeGroup(@PathVariable int age){
GroupOperation groupByDept=Aggregation.group("age").count().as("count");
MatchOperation matchoperation=Aggregation.match(new Criteria("count").is(age));
SortOperation sortoperation=Aggregation.sort(Sort.by(Sort.Direction.DESC, "count"));
Aggregation aggregation=Aggregation.newAggregation(groupByDept,matchoperation, sortoperation);
AggregationResults<AgeCount> results=mongoTemplate.aggregate(aggregation, "employees", AgeCount.class);
//return mongoTemplate.find("", Employee.class);
return results.getMappedResults();
}
}
package com.nisum.springboot.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.nisum.springboot.entity.Publisher;
import com.nisum.springboot.repository.PublisherRepository;
@RestController
@RequestMapping("/publisher")
public class PublisherController {
@Autowired
private PublisherRepository publisherRepository;
@PostMapping
public Publisher savePublisher(@RequestBody Publisher publisher) {
return publisherRepository.save(publisher);
}
@GetMapping
public List<Publisher> getPublishers() {
return publisherRepository.findAll();
}
@GetMapping("/{title}")
public List<Publisher> getPublisher(@PathVariable String title) {
return publisherRepository.getBookDetails(title);
}
}
package com.nisum.springboot.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.nisum.springboot.entity.Mobile;
import com.nisum.springboot.entity.User;
import com.nisum.springboot.service.UserService;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public User saveUser(@RequestBody User user) {
return userService.saveUser(user);
}
@GetMapping("/userByName/{name}")
public List<User> getUserByName(@PathVariable String name) {
return userService.getUserByName(name);
}
@GetMapping("/userByCity/{city}")
public List<User> getUserByCity(@PathVariable String city) {
return userService.getUserByCity(city);
}
@GetMapping("/getMobilesByUserName/{name}")
public List<User> getMobilesByUserName(@PathVariable String name) {
return userService.getMobilesByUserName(name);
}
}
package com.nisum.springboot.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AgeCount {
private int id;
private int count;
}
package com.nisum.springboot.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Address {
private String city;
private String state;
private String pincode;
}
package com.nisum.springboot.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "books")
public class Book {
@Id
private String id;
private String isbn13;
private String title;
private int pages;
}
package com.nisum.springboot.entity;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "employees")
public class Employee {
private String id;
private String name;
private String firstname;
private String lastname;
private int age;
private String department;
}
package com.nisum.springboot.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Mobile {
private String name;
private Double price;
}
package com.nisum.springboot.entity;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "publishers")
public class Publisher {
@Id
private String id;
private String name;
private String arconym;
private int foundationYear;
private List<Book> books;
}
package com.nisum.springboot.entity;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "users")
public class User {
@Id
private String id;
private String name;
private String gender;
private Address address;
private List<Mobile> mobiles;
}
package com.nisum.springboot.repository;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;
import com.nisum.springboot.entity.Employee;
@Repository
public interface EmployeeRepository extends MongoRepository<Employee, String>{
@Query("{'name' : ?0}")
List<Employee> findByName(String name);
List<Employee> findByNameOrderByDepartment(String name);
//here 0 for exclusion & 1 for inclusion
@Query(value="{name: ?0}" , fields = "{'firstname' : 1,'department' : 1, 'age' : 1, _id : 0}")
//@Query(value="{name: ?0}" , fields = "{'lastname' : 0, 'age' : 0}")
List<Employee> getNameValues(String name);
//@Query("{name: {'$regex' : '?0' } }")
@Query("{name: {'$regex' : '?0', '$options' : 'i' } }") // like %%
List<Employee> getEmployeeByReg(String name);
//Query("{'age' : {'$gt' : ?0} }")
@Query("{'age' : { '$gte' : ?0, '$lte' : ?1 } }")
List<Employee> getEmployeesAgeBetween(int minage, int maxage);
@Query("{'name' : ?0 , 'department' : ?1}")
List<Employee> findByNameAndDept(String name, String department);
}
package com.nisum.springboot.repository;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import com.nisum.springboot.entity.Publisher;
public interface PublisherRepository extends MongoRepository<Publisher, String>{
@Query("{'books.title' : ?0}")
List<Publisher> getBookDetails(String title);
}
package com.nisum.springboot.repository;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;
import com.nisum.springboot.entity.Mobile;
import com.nisum.springboot.entity.User;
@Repository
public interface UserRepository extends MongoRepository<User, String>{
List<User> findByName(String name);
@Query("{'address.city':?0}")
List<User> findByCity(String city);
@Query("{'mobiles.name':?0}")
List<User> getMobilesByUserName(String name);
}
package com.nisum.springboot.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nisum.springboot.entity.Employee;
import com.nisum.springboot.repository.EmployeeRepository;
@Service
public class EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
public List<Employee> saveEmployees(List<Employee> employees) {
return employeeRepository.saveAll(employees);
}
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}
public List<Employee> findByName(String name){
return employeeRepository.findByNameOrderByDepartment(name);
//return employeeRepository.getNameValues(name);
//return employeeRepository.getEmployeeByReg(name);
//return employeeRepository.findByNameOrderByDepartment(name);
}
public List<Employee> findByNameAndDept(String name, String department) {
return employeeRepository.findByNameAndDept(name, department);
}
public List<Employee> getEmployeesAgeBetween(int minage, int maxage) {
return employeeRepository.getEmployeesAgeBetween(minage,maxage);
}
}
package com.nisum.springboot.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nisum.springboot.entity.Mobile;
import com.nisum.springboot.entity.User;
import com.nisum.springboot.repository.UserRepository;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User saveUser(User user) {
return userRepository.save(user);
}
public List<User> getUserByName(String name) {
return userRepository.findByName(name);
}
public List<User> getUserByCity(String city) {
return userRepository.findByCity(city);
}
public List<User> getMobilesByUserName(String name) {
return userRepository.getMobilesByUserName(name);
}
}
spring.mvc.pathmatch.matching-strategy=ant-path-matcher
\ No newline at end of file
......@@ -2,6 +2,8 @@ server:
port: 8888
spring:
jackson:
default-property-inclusion: non_default
data:
mongodb:
host: localhost
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment