MongoDB: Spring Boot (Java)
Accessing MongoDB via Spring Boot
This repo has a demo:
See also:
Setting up Spring Boot with MongoDB
Setting up the data object
The first step is to set up a plain old java object that:
- has private data members for the data you want
- follows the Java Bean standard (no-arg constructor, getters, setters)
- has a special attribute:
@Id private String id;
which uses the annotation:import org.springframework.data.annotation.Id;
Here’s an example, using Lombok (https://projectlombok.org/) to set up the Java Bean boilerplate stuff.
This also sets up a constructor for all of the required arguments (the ones we mark with@NonNull
), which is usually everything except for theid
.
package edu.ucsb.cs56.pconrad.mlab.mlabdemo;
import lombok.Data;
import lombok.RequiredArgsConstructor; // generates constructor for fields marked with @NonNull
import lombok.NoArgsConstructor; // @NonNull property ignored by this constructor
import lombok.NonNull;
import org.springframework.data.annotation.Id;
@Data
@NoArgsConstructor
@RequiredArgsConstructor
public class BuildingCode {
@Id private String id;
@NonNull private String code;
@NonNull private String name;
}
More on MongoDB: Spring Boot (Java)
- MongoDB: Java—Accessing MongoDB via Java
- MongoDB: MLab—A specific cloud provider of MongoDB services
- MongoDB: MLab Database Creation—Setting up a new database
- MongoDB: MLab Databases, Users and Collections—Next steps after creating a database
- MongoDB: Python—Accessing MongoDB via Python
- MongoDB: Spring Boot (Java)—Accessing MongoDB via Spring Boot