This blog represents code required to create a Spring boot application that uses Spring Data MongoRepository interface to connect with MongoDB database.
Create a new Spring Starter Project using Eclipse IDE. This would create a class annotated with @SpringBootAnnotation.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
Create a Configuration class which is used to instantiate a MongoClient for connecting with MongoDB database.
package com.vflux.demo.config; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.data.mongodb.config.AbstractMongoConfiguration; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import com.mongodb.Mongo; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; @Configuration @EnableMongoRepositories(basePackages = "com.vflux.demo.repository") @PropertySource("classpath:application.properties") public class MongoConfig extends AbstractMongoConfiguration { @Value("${mongodb.name}") private String dbName; @Value("${mongodb.authDB}") private String authDB; @Value("${mongodb.host}") private String host; @Value("${mongodb.port}") private String port; @Value("${mongodb.username}") private String username; @Value("${mongodb.password}") private String password; @Override protected String getDatabaseName() { return this.dbName; } @Override public Mongo mongo() throws Exception { List<ServerAddress> seeds = new ArrayList<ServerAddress>(); seeds.add( new ServerAddress(this.host, Integer.parseInt(this.port.trim())) ); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); MongoCredential userCredential = MongoCredential.createCredential(this.username, this.authDB, this.password.toCharArray()); credentials.add(userCredential); return new MongoClient( seeds, credentials ); } @Override protected String getMappingBasePackage() { return "com.vflux.demo"; } }
# MongoDB properties mongodb.name=vitalflux mongodb.host=localhost mongodb.port=27017 mongodb.username=ajitesh mongodb.password=vitalflux mongodb.authDB=vitalflux
Place following code in SpringBootAnnotation class for invoking MongoRepository instance (UserDAO in the code given below). In ideal scenario, you would want to invoke this DAO class from a service class.
package com.vflux.demo; import java.util.concurrent.ThreadLocalRandom; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.vflux.demo.domain.User; import com.vflux.demo.repository.UserDAO; @SpringBootApplication public class DemoAppApplication { private static UserDAO userDAO; @Autowired public void setPersonCountDAO(UserDAO userDAO) { this.userDAO = userDAO; } public static void main(String[] args) { SpringApplication.run(DemoAppApplication.class, args); createUser(); } private static void createUser() { User user = new User(); user.setFirstname("Calvin"); user.setLastname("Hobbes"); user.setAge(20); user.setLocation("Hyderabad"); userDAO.insert(user); } }
package com.vflux.demo.repository; import org.springframework.data.mongodb.repository.MongoRepository; import com.vflux.demo.domain.User; public interface UserDAO extends MongoRepository<User, String> { User insert(User user); }
In the above code, a User class is used. The User class can represent a collection in MongoDB with name as user.
package com.vflux.demo.domain; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document public class User { @Id private String id; private String firstname; private String middlename; private String lastname; private int age; private String location; private String role; public User() {} public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getMiddlename() { return middlename; } public void setMiddlename(String middlename) { this.middlename = middlename; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } }
In recent years, artificial intelligence (AI) has evolved to include more sophisticated and capable agents,…
Adaptive learning helps in tailoring learning experiences to fit the unique needs of each student.…
With the increasing demand for more powerful machine learning (ML) systems that can handle diverse…
Anxiety is a common mental health condition that affects millions of people around the world.…
In machine learning, confounder features or variables can significantly affect the accuracy and validity of…
Last updated: 26 Sept, 2024 Credit card fraud detection is a major concern for credit…