This is a hands-on page for building a REST API using Spring Boot using MongoDB as a data store. Since it is a training rush, the goal is to easily summarize the procedures in sequence and copy them so that you can easily experience them.
The content itself is almost the following copy and paste. I wanted to use Gradle, so I changed the content a little. https://stackabuse.com/spring-data-mongodb-tutorial/
Create a REST API using Spring Boot. Use MongoDB for datastore and CRUD MongoDB data on request
The finished product is listed on GitHub below, so please refer to it if it doesn't work. https://github.com/theMistletoe/MongoDB-SpringBoot-sample
Sign up for MongoDB https://account.mongodb.com/account/register
After signing up, click "Build a Cluster"
I want to do it for free, so choose FREE
cluster settings. You don't have to change it.
The cluster construction will start.
After building the cluster, first create a user for Database access.
Select password authentication and enter the user name and password to create a user. Remember this username and password as you will use them later.
User was created
Next, set up Network Access. You can define a whitelist using IP addresses, so let's set it to accept any IP address for practice. (Since security is loose for practice, please do not use it in production)
Click [ALLOW ACCESS FROM ANYWHERE] to confirm
Let's make a DB Click on Clusters COLLECTIONS
Click Add My Own Data
Enter "jobs" for the database name and "candidate" for the collection name to create
After creating the database, the console screen will be displayed. Later data updates will be reflected here.
This is the end of MongoDB setup.
Go to Spring Initializr, set the template as shown in the image, and download the zip with Generate.
Unzip the zip and open it in IntelliJ. First, open application.properties and set MongoDB access information.
spring.data.mongodb.uri=mongodb+srv://user:<password>@cluster0.ayoho.mongodb.net/<dbname>?retryWrites=true&w=majority
You can get the settings for spring.data.mongodb.uri from the MongoDB console.
Use the password and dbname set during MongoDB setup. (If you follow the procedure, dbname will be "jobs")
Now let's write Java. I can't explain the detailed implementation, so please try to write while solving any unclear points. You can place it anywhere, but please refer to the package information or refer to GitHub.
Candidate.java
package com.example.mongoDBsample.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "candidate")
public class Candidate {
@Id
private String id;
private String name;
private double exp;
@Indexed(unique = true)
private String email;
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 getExp() {
return exp;
}
public void setExp(double exp) {
this.exp = exp;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
CandidateRepository.java
package com.example.mongoDBsample.repository;
import com.example.mongoDBsample.entity.Candidate;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
import java.util.Optional;
public interface CandidateRepository extends MongoRepository<Candidate, String> {
Optional<Candidate> findByEmail(String email);
List<Candidate> findByExpGreaterThanEqual(double exp);
List<Candidate> findByExpBetween(double from, double to);
}
CandidateController.java
package com.example.mongoDBsample.controller;
import com.example.mongoDBsample.exception.ResourceNotFoundException;
import com.example.mongoDBsample.entity.Candidate;
import com.example.mongoDBsample.repository.CandidateRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/candidate")
public class CandidateController {
@Autowired
private CandidateRepository candidateRepository;
@PostMapping
@ResponseStatus(code = HttpStatus.CREATED)
public Candidate add(@RequestBody Candidate candidate) {
return candidateRepository.save(candidate);
}
@GetMapping
public List<Candidate> getAll() {
return candidateRepository.findAll();
}
@GetMapping(value = "/{id}")
public Candidate getOne(@PathVariable String id) {
return candidateRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException());
}
@PutMapping(value = "/{id}")
public Candidate update(@PathVariable String id, @RequestBody Candidate updatedCandidate) {
Candidate candidate = candidateRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException());
candidate.setName(updatedCandidate.getName());
candidate.setExp(updatedCandidate.getExp());
candidate.setEmail(updatedCandidate.getEmail());
return candidateRepository.save(candidate);
}
@DeleteMapping(value = "/{id}")
@ResponseStatus(code = HttpStatus.ACCEPTED)
public void delete(@PathVariable String id) {
Candidate candidate = candidateRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException());
candidateRepository.delete(candidate);
}
@GetMapping("/searchByEmail")
public Candidate searchByEmail(@RequestParam(name = "email") String email) {
return candidateRepository.findByEmail(email)
.orElseThrow(() -> new ResourceNotFoundException());
}
@GetMapping("/searchByExp")
public List<Candidate> searchByExp(@RequestParam(name = "expFrom") Double expFrom, @RequestParam(name = "expTo", required = false) Double expTo) {
List<Candidate> result = new ArrayList<>();
if (expTo != null) {
result = candidateRepository.findByExpBetween(expFrom, expTo);
} else {
result = candidateRepository.findByExpGreaterThanEqual(expFrom);
}
return result;
}
}
ResourceNotFoundException.java
package com.example.mongoDBsample.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException() {
}
}
Now that the implementation is complete, let's check if data access is possible via the API.
Launch the app in IntelliJ
Or execute the following with CUI to start
./gradlew bootRun
First, let's register the user. If you send a POST request to http: // localhost: 8080 / candidate / with the following JSON object attached to the body, The registered user information will be returned in the response.
{
"name": "Axel",
"exp": "10",
"email": "[email protected]"
}
If you look at the MongoDB console, you can see that the data has been added.
If you send a GET request to http: // localhost: 8080 / candidate, all registered users will be returned.
In a PUT request to http: // localhost: 8080 / candidate / {user id} If you attach the updated JSON object to the body, the registration information will be updated.
By throwing a DELETE request to http: // localhost: 8080 / candidate / {user id} You can delete the user.
that's all.
I think you've created MongoDB / SpringBoot to implement the basics of a REST API backend that allows you to use your datastore. Let's extend this and create an application in cooperation with the front end!
Recommended Posts