Spring Boot with MongoDB
Spring Boot with MongoDB
spring.data.mongodb.uri
Single property enable us to connect MongoDB Database
spring.data.mongodb.uri=mongodb://localhost:27017/college
Mapping domain types to documents
Spring Data MongoDB offers a handful of annotations that
are useful for mapping domain types to document
structures to be persisted in MongoDB.
@Id—Designates a property as the document ID (from Spring Data
Commons)
@Document—Declares a domain type as a document to be persisted to
MongoDB
Step1: Create Domain Class
@Document(collection="students")
public class Students {
@Id
private ObjectId _id;
private String name;
private String email;
private String phone;
public ObjectId get_id() {
return _id;
}
public void set_id(ObjectId _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Writing reactive MongoDB repository interfaces
Step2: Create Mongo Repository Interface
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends ReactiveMongoRepository<Students,ObjectId>
{
}
ReactiveMongoRepository provides implementation for the following database tasks
• Store new data
• Search an existing data
• Update existing data
• Delete existing data
• Display All data
Step3: Create Rest Controller Service
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/getAll")
public Flux<Students> getAllUsers(){
return userRepository.findAll();
}
@GetMapping("/getOne/{id}")
public Mono<Students> getUserById(@PathVariable ObjectId id){
return userRepository.findById(id);
}
@PostMapping("/addUser")
public Mono<Students> addUser(@RequestBody Students students){
return userRepository.save(students);
}
}
Testing 1: View All Documents from mongodb
Testing 2: Search a document using Object_id from mongodb
Testing 3: Add a new document to mongodb database
New document
added for
“reban”