SpringBoot MongoDB integration:

MongoDB is an opensource NoSQL database which is opensource too. In this following program learn how to configure spring boot MongoDB with maven examples. Here is Configuration of spring boot MongoDB example with maven.

Pom.xml

<?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"> <modelVersion>4.0.0</modelVersion> <groupId>com.spring-boot-mongodb</groupId> <artifactId>Spring-Boot-Mongo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>Spring-Boot-Mongo Maven Webapp</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <finalName>Spring-Boot-Mongo</finalName> </build> </project>

Application.properties

logging.level.org.springframework.web=DEBUG #Mongo spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 spring.data.mongodb.database=sampledb

UserRepository.java

package com.candidjava.spring.repository; import org.springframework.data.repository.CrudRepository; import com.candidjava.spring.bean.User; public interface UserRepository extends CrudRepository<User, String>{ }

UserController.java

package com.candidjava.spring.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponentsBuilder; import com.candidjava.spring.bean.User; import com.candidjava.spring.service.UserService; @RestController @RequestMapping(value={"/","/user"}) public class UserController { @Autowired UserService userService; @GetMapping(value="/",produces = MediaType.APPLICATION_JSON_VALUE) public String get(){ return "Please give url as Spring-Boot-Rest/user/get"; } @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<User> getUserById(@PathVariable("id") String id) { System.out.println("Fetching User with id " + id); User user = userService.findById(id); if (user == null) { return new ResponseEntity<User>(HttpStatus.NOT_FOUND); } return new ResponseEntity<User>(user, HttpStatus.OK); } @PostMapping(value="/create",headers="Accept=application/json") public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder){ System.out.println("Creating User "+user.getName()); userService.createUser(user); HttpHeaders headers = new HttpHeaders(); headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri()); return new ResponseEntity<Void>(headers, HttpStatus.CREATED); } @GetMapping(value="/get", headers="Accept=application/json") public List<User> getAllUser() { List<User> tasks=userService.getUser(); return tasks; } @PutMapping(value="/update", headers="Accept=application/json") public ResponseEntity<String> updateUser(@RequestBody User currentUser) { System.out.println("sd"); User user = userService.findById(currentUser.getId()); if (user==null) { return new ResponseEntity<String>(HttpStatus.NOT_FOUND); } userService.update(currentUser, currentUser.getId()); return new ResponseEntity<String>(HttpStatus.OK); } @DeleteMapping(value="/{id}", headers ="Accept=application/json") public ResponseEntity<User> deleteUser(@PathVariable("id") String id){ User user = userService.findById(id); if (user == null) { return new ResponseEntity<User>(HttpStatus.NOT_FOUND); } userService.deleteUserById(id); return new ResponseEntity<User>(HttpStatus.NO_CONTENT); } @PatchMapping(value="/{id}", headers="Accept=application/json") public ResponseEntity<User> updateUserPartially(@PathVariable("id") String id, @RequestBody User currentUser){ User user = userService.findById(id); if(user ==null){ return new ResponseEntity<User>(HttpStatus.NOT_FOUND); } User usr = userService.updatePartially(currentUser, id); return new ResponseEntity<User>(usr, HttpStatus.OK); } }

User.java

package com.candidjava.spring.bean; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @SuppressWarnings("serial") @Document(collection = "user") public class User extends BaseEntity{ private String country; private String name; public User(){ } public User(String country, String name){ this.country = country; this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } }

BaseEntity.java

package com.candidjava.spring.bean; import java.io.Serializable; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @SuppressWarnings("serial") @Document public abstract class BaseEntity implements Serializable { @Id private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } }

UserService.java

package com.candidjava.spring.service; import java.util.List; import com.candidjava.spring.bean.User; public interface UserService { public void createUser(User user); public List<User> getUser(); public User findById(String id); public User update(User user, String l); public void deleteUserById(String id); public User updatePartially(User user, String id); }

UserServiceImp.java

package com.candidjava.spring.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.candidjava.spring.bean.User; import com.candidjava.spring.repository.UserRepository; @Service @Transactional public class UserServiceImp implements UserService { @Autowired UserRepository userRepository; public void createUser(User user) { // TODO Auto-generated method stub userRepository.save(user); } public List<User> getUser() { // TODO Auto-generated method stub return (List<User>) userRepository.findAll(); } public User findById(String id) { // TODO Auto-generated method stub return userRepository.findOne(id); } public User update(User user, String l) { // TODO Auto-generated method stub return userRepository.save(user); } public void deleteUserById(String id) { // TODO Auto-generated method stub userRepository.delete(id); } public User updatePartially(User user, String id) { // TODO Auto-generated method stub User usr = findById(id); usr.setCountry(user.getCountry()); return userRepository.save(usr); } }

Application.java

package com.candidjava; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

Output:

Request method:post endpoint: http://localhost:8080/user/create Content-Type:application/json body: { "country":"India", "name":"Mathan" } Response Status: 201 Request method:GET endpoint: http://localhost:8080/user/get Content-Type:application/json Response Status: 200 content: [{"id":"5afec0ad72637160400936b6","country":"India","name":"Mathan"}]

DOWNLOAD Source File