Posted In: Spring, Spring Boot, Spring Data

Spring Boot + Spring Data MongoDB + MongoDB – Complexity1

Technologies used

1. Spring Boot 1.5.6

2. Spring data commons 1.13.6

3. Spring data mongodb 1.10.6

4. MongoDB driver 3.4.2

5. MongoDB server 3.4.6

Steps

1. Create Spring Boot starter project or download and import example source project from this link

2. Verify maven pom.xml to have spring-boot-starter, Spring data mongodb, spring-boot-starter-test

3. Add application properties

4. Create MongoDB database and collection

5. Map the POJO with MongoDB Document

6. Implement MongoRepository interface

7. Test User Repository

1. Create Spring Boot starter project

2. Verify maven pom.xml

<dependencies>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>
</dependencies>

3. Add application properties

spring.data.mongodb.uri=mongodb://localhost:27017/javausecase_db

4. Follow these steps to install and set up MongoDB. Skip to step 5 if you already have DB and Collection setup.

4a. To download and install locally go to MongoDB

4b. Start the server

E:\programs\MongoDB\Server\3.4\bin>mongod --dbpath=E:\programs\MongoDB\Server\3.4\data

4c. Use MongoDB client to create “javausecase_db” and “users” collection. I am using Robo 3T

5. Map the POJO properties with Database table columns

@Document- Name of the collection.

@Id – Primary key column

import java.io.Serializable;
import java.util.Date;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "users")
public class User implements Serializable {
	private static final long serialVersionUID = 65007985219089594L;

	@Id
	private Long userId;
	private String userLoginId;
	private String userPassword;
	private String firstName;
	private String lastName;
	private Date dateofBirth;
	private String emailId;
        
        //GETTERS AND SETTERS .....
}

6. Implement MongoRepository interface

package com.example.springapp;

import java.util.Date;
import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface UserRepository extends MongoRepository<User, Long> {
	List<User> findByEmailId(String emailId);

	List<User> findByDateofBirth(Date date);
}

7. Test User Repository

package com.example.springapp;

import java.text.SimpleDateFormat;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class UserRepositoryTest {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserRepositoryTest.class);

	@Test
	public void contextLoads() {
	}

	@Autowired
	UserRepository userRepository;

	@Test
	public void testUserRepository() throws Exception {
		LOGGER.debug("Running testUserRepository()....");

		User newUser = new User();
		newUser.setUserId(System.currentTimeMillis());
		newUser.setFirstName("Abhijit");
		newUser.setLastName("Pednekar");
		newUser.setDateofBirth(new 
				SimpleDateFormat("yyyy-MM-dd").parse("1976-09-09"));
		newUser.setEmailId("abh@as.com");
		newUser.setUserLoginId("abhijit");
		newUser.setUserPassword("password");

		userRepository.save(newUser);

		LOGGER.debug("\n\nfindByAll()");
		for (User user : userRepository.findAll()) {
			LOGGER.debug(user.toString());
		}

		LOGGER.debug("\n\nfindByEmailId(String emailId)");
		for (User user : userRepository.findByEmailId("abh@as.com")) {
			LOGGER.debug(user.toString());
		}

		LOGGER.debug("\n\nfindByDateofBirth(Date date)");
		for (User user : userRepository.findByDateofBirth(
				new SimpleDateFormat("yyyy-MM-dd").parse("1976-09-09"))) {
			LOGGER.debug(user.toString());
		}

	}
}

 

 

by , on July 28th, 2017

  • Categories