文章目錄
本文講解Spring Boot基礎下,如何使用MongoDB,編寫數據訪問。
環境依賴
修改 POM 文件,添加spring-boot-starter-data-mongodb依賴。
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-mongodb</artifactId>
- </dependency>
數據源
方案一 使用 Spring Boot 默認配置
MongoDB 使用,在 Spring Boot 中同樣提供了自配置功能。
默認使用localhost:27017的名稱叫做test的數據庫。
此外,我們也可以在 src/main/resources/application.properties 中配置數據源信息。
- spring.data.mongodb.uri=mongodb://localhost:27017/springboot-db
如果存在密碼,配置改成如下
- spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/dbname
方案二 手動創建
通過 Java Config 創建mongoTemplate。
- @Configuration
- @EnableMongoRepositories
- public class MongoConfig extends AbstractMongoConfiguration {
- private String mongoHost = "localhost";
- private int mongoPort = 27017;
- private String dbName = "springboot-db";
- private static final String MONGO_BASE_PACKAGE = "com.lianggzone.springboot.action.data.mongodb.entity";
- @Autowired
- private ApplicationContext appContext;
- @Override
- protected String getDatabaseName() {
- return dbName;
- }
- @Override
- public Mongo mongo() throws Exception {
- MongoClient mongoClient = new MongoClient(mongoHost, mongoPort);
- return mongoClient;
- }
- @Override
- protected String getMappingBasePackage() {
- return MONGO_BASE_PACKAGE;
- }
- @Override
- @Bean
- public MongoTemplate mongoTemplate() throws Exception {
- return new MongoTemplate(mongo(), getDatabaseName());
- }
- }
使用mongoTemplate操作
實體對象
- @Document(collection = "author")
- public class Author {
- @Id
- private Long id;
- private String realName;
- private String nickName;
- // SET和GET方法
- }
DAO相關
我們通過mongoTemplate進行數據訪問操作。
- @Repository
- public class AuthorDao {
- @Autowired
- private MongoTemplate mongoTemplate;
- public void add(Author author) {
- this.mongoTemplate.insert(author);
- }
- public void update(Author author) {
- this.mongoTemplate.save(author);
- }
- public void delete(Long id) {
- Query query = new Query();
- query.addCriteria(Criteria.where("_id").is(id));
- this.mongoTemplate.remove(query, Author.class);
- }
- public Author findAuthor(Long id) {
- return this.mongoTemplate.findById(id, Author.class);
- }
- public List<Author> findAuthorList() {
- Query query = new Query();
- return this.mongoTemplate.find(query, Author.class);
- }
- }
Service相關
Service層調用Dao層的方法,這個是典型的套路。
- @Service
- public class AuthorService {
- @Autowired
- private AuthorDao authorDao;
- public void add(Author author) {
- this.authorDao.add(author);
- }
- public void update(Author author) {
- this.authorDao.update(author);
- }
- public void delete(Long id) {
- this.authorDao.delete(id);
- }
- public Author findAuthor(Long id) {
- return this.authorDao.findAuthor(id);
- }
- public List<Author> findAuthorList() {
- return this.authorDao.findAuthorList();
- }
- }
Controller相關
為了展現效果,我們先定義一組簡單的 RESTful API 接口進行測試。
- @RestController
- @RequestMapping(value="/data/mongodb/author")
- public class AuthorController {
- @Autowired
- private AuthorService authorService;
- /**
- * 查詢用戶列表
- */
- @RequestMapping(method = RequestMethod.GET)
- public Map<String,Object> getAuthorList(HttpServletRequest request) {
- List<Author> authorList = this.authorService.findAuthorList();
- Map<String,Object> param = new HashMap<String,Object>();
- param.put("total", authorList.size());
- param.put("rows", authorList);
- return param;
- }
- /**
- * 查詢用戶信息
- */
- @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
- public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
- Author author = this.authorService.findAuthor(userId);
- if(author == null){
- throw new RuntimeException("查詢錯誤");
- }
- return author;
- }
- /**
- * 新增方法
- */
- @RequestMapping(method = RequestMethod.POST)
- public void add(@RequestBody JSONObject jsonObject) {
- String userId = jsonObject.getString("user_id");
- String realName = jsonObject.getString("real_name");
- String nickName = jsonObject.getString("nick_name");
- Author author = new Author();
- if (author!=null) {
- author.setId(Long.valueOf(userId));
- }
- author.setRealName(realName);
- author.setNickName(nickName);
- try{
- this.authorService.add(author);
- }catch(Exception e){
- e.printStackTrace();
- throw new RuntimeException("新增錯誤");
- }
- }
- /**
- * 更新方法
- */
- @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.PUT)
- public void update(@PathVariable Long userId, @RequestBody JSONObject jsonObject) {
- Author author = this.authorService.findAuthor(userId);
- String realName = jsonObject.getString("real_name");
- String nickName = jsonObject.getString("nick_name");
- author.setRealName(realName);
- author.setNickName(nickName);
- try{
- this.authorService.update(author);
- }catch(Exception e){
- e.printStackTrace();
- throw new RuntimeException("更新錯誤");
- }
- }
- /**
- * 刪除方法
- */
- @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.DELETE)
- public void delete(@PathVariable Long userId) {
- try{
- this.authorService.delete(userId);
- }catch(Exception e){
- throw new RuntimeException("刪除錯誤");
- }
- }
- }
總結
上面這個簡單的案例,讓我們看到了 Spring Boot 整合 MongoDB 的整個流程。實際上,與 Spring 4 中 通過 Spring Data MongoDB 整合 MongoDB 是相同的, Spring Boot 默認集成了一些配置信息,但是個人更加偏向於方案二的手動創建方式,有更好的擴展性。
源代碼
相關示例完整代碼: springboot-action
(完)
