Spring Boot Mongo DB
Preparation MongoDB
Let’s start to use MongoDB
For Mac user, brew is easiest way to install mongodb.
brew install mongodb
Start with data directory(before it, please create empty directory named “mongodata”)
mongod --dbpath ./mongodata
Run with empty mongo environment
Spring Boot Dependencies
To use mongodb in Spring Boot, JPA mongod is easy
Add following dependency to build.gradle
compile("org.springframework.boot:spring-boot-starter-data-mongodb")
I also use lombok for getter/setter
Default Database
Let’s prepare Entity class and Repository to work with mongo.
By default, mongo library uses mongodb://localhost/test
Entity
@Data public class Customer { @Id private String id; private String firstName; private String lastName; public Customer() { } public Customer(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } }
The key point is @Id
Repository
public interface CustomerRepository extends MongoRepository<Customer, String> { public Customer findByFirstName(String firstName); public List<Customer> findByLastName(String lastName); }
Controller
@RestController @RequestMapping("/mongo") public class MongoController { @Autowired CustomerRepository customerRepository; @RequestMapping(value="/list", method=RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) public List<Customer> find() { return customerRepository.findAll(); } @RequestMapping(value="/create", method=RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE }) public Customer create(@RequestParam Map<String, String>params) { Customer customer = new Customer(params.get("firstname"), params.get("lastname")); customerRepository.save(customer); return customer; } }
You can test to create new user with POST: localhost:8080/mongo/create?firstname=xxx&lastname=xxx
You can test json response all customers with GET: localhost:8080/mongo/list
Create User and Database Settings
Next is advanced topic. By default, library uses root user. It’s not good for security.
Create new user for this database
mongo > use crm > db.createUser({user: "guser", pwd:"password", roles:[{role:"readWrite", db:'crm'}]})
Create crm database and new user(name: guser, password: password) This has readWrite only for crm database.
Mongo side was done.
Next is setting for Spring Boot side.
Mongo setting should be in application.yml src/main/resources/application.yml
spring: data: mongodb: uri: mongodb://guser:password@localhost:27017/crm
Source codes are same.