springboot整合Mongodb
程序员文章站
2022-07-12 23:15:14
...
springboot整合Mongodb
1.增加依赖
注意:springboot其实还是整合的spring-data-mongodb,通过spring-data去操作MongoDB数据库
<!-- springboot整合Mongodb(1) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2.配置mongodb连接信息(在application.properties中)
# springboot整合Mongodb(2)
# 验证登录信息的库
spring.data.mongodb.authentication-database=hamsv4_developer
# 要连接使用的库
spring.data.mongodb.database=hamsv4_developer
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.username=admin
spring.data.mongodb.password=admin
由于我配置了多数据源,因此配置信息放入生产环境配置文件中(application-project.properties)
约定的不同的环境下配置文件名称设定
3.定义mongodb接口DAO
```java
package com.steno.propertiestest.dao.mongodbDao;
public interface MongodbDao {
/**
* mongodb保存数据
* @param object
*/
public void saveMongo(Object object);
}
4.定义mongodb接口DAO的实现类,并注入MongoTemplate操作模板类
```java
package com.steno.propertiestest.dao.mongodbDao.impl;
import com.steno.propertiestest.dao.mongodbDao.MongodbDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
@Component
public class MongodbDaoImpl implements MongodbDao {
@Autowired
private MongoTemplate mongoTemplate;
public void saveMongo(Object object){
mongoTemplate.save(object);
}
}
5.定义controller测试
package com.steno.propertiestest.controller;
import com.steno.propertiestest.dao.mongodbDao.MongodbDao;
import com.steno.propertiestest.vo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MongodbController {
@Autowired
private MongodbDao mongodbDao;
@GetMapping("saveMongo")
public String saveMongo(){
Book book = new Book();
book.setPrice("100");
book.setAuthor("mongo");
book.setName("mongodb");
mongodbDao.saveMongo(book);
return "新增mongodb数据成功!";
}
}
如果所示:
6.访问测试及结果展示:
http://localhost:8081/project/saveMongo
数据库展示:
上一篇: springboot整合mongoDB
下一篇: Spring Boot集成Shiro