在boot中操作mongodb也是非常的方便,如果是没有使用boot的项目,可以参考我之前的文章spring-data-mongodb之环境准备 看了之后你就会知道boot中使用mongodb在配置方面有多么简洁了。
今天只介绍怎么集成spring data mongodb,具体的用法请参考我博客之前的文章。
首先我们在pom.xml中加入mongodb的模块依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
然后在application.properties中配置mongodb的链接信息
# Database name.
spring.data.mongodb.database=test
# Mongo server host.
spring.data.mongodb.host=localhost
# Mongo server port.
spring.data.mongodb.port=27017
我这边只配置最基本的信息,用户也没有创建,更多配置信息请参考下面
# MONGODB (MongoProperties)
spring.data.mongodb.authentication-database= # Authentication database name.
spring.data.mongodb.database=test # Database name.
spring.data.mongodb.field-naming-strategy= # Fully qualified name of the FieldNamingStrategy to use.
spring.data.mongodb.grid-fs-database= # GridFS database name.
spring.data.mongodb.host=localhost # Mongo server host.
spring.data.mongodb.password= # Login password of the mongo server.
spring.data.mongodb.port=27017 # Mongo server port.
spring.data.mongodb.repositories.enabled=true # Enable Mongo repositories.
spring.data.mongodb.uri=mongodb://localhost/test # Mongo database URI. When set, host and port are ignored.
spring.data.mongodb.username= # Login user of the mongo server.
配置好了之后我们就可以直接操作mongodb了
MongoTemplate方式操作
直接用 @Autowired注解就可以注入MongoTemplate 对象了
@Component
public class StudentDao {
private final MongoTemplate mongoTemplate;
@Autowired
public StudentDao(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
public void addStudent(Student studnet) {
mongoTemplate.save(studnet);
}
public List<Student> queryStudents(){
return mongoTemplate.find(null, Student.class);
}
}
Repository方式操作
public interface StudentRepository extends MongoRepository<Student, String> {
public Student findByName(String name);
}
直接可以在controller里面调用StudentService 里面注入StudentDao就可以了
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@Autowired
private StudentRepository studentRepository;
@RequestMapping("/students")
Object queryStudents() {
return studentService.queryStudents();
}
@RequestMapping("/students/{name}")
Object queryStudentByName(@PathVariable String name) {
return studentRepository.findByName(name);
}
}