Spring Boot 揭秘與實戰(二) 數據存儲篇 - MongoDB


文章目錄

  1. 1. 環境依賴
  2. 2. 數據源
    1. 2.1. 方案一 使用 Spring Boot 默認配置
    2. 2.2. 方案二 手動創建
  3. 3. 使用mongoTemplate操作4. 總結
    1. 3.1. 實體對象
    2. 3.2. DAO相關
    3. 3.3. Service相關
    4. 3.4. Controller相關
  4. 5. 源代碼

本文講解Spring Boot基礎下,如何使用MongoDB,編寫數據訪問。

環境依賴

修改 POM 文件,添加spring-boot-starter-data-mongodb依賴。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-mongodb</artifactId>
  4. </dependency>

數據源

方案一 使用 Spring Boot 默認配置

MongoDB 使用,在 Spring Boot 中同樣提供了自配置功能。

默認使用localhost:27017的名稱叫做test的數據庫。

此外,我們也可以在 src/main/resources/application.properties 中配置數據源信息。

  1. spring.data.mongodb.uri=mongodb://localhost:27017/springboot-db

如果存在密碼,配置改成如下

  1. spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/dbname

方案二 手動創建

通過 Java Config 創建mongoTemplate。

  1. @Configuration
  2. @EnableMongoRepositories
  3. public class MongoConfig extends AbstractMongoConfiguration {
  4.  
  5. private String mongoHost = "localhost";
  6. private int mongoPort = 27017;
  7. private String dbName = "springboot-db";
  8.  
  9. private static final String MONGO_BASE_PACKAGE = "com.lianggzone.springboot.action.data.mongodb.entity";
  10.  
  11. @Autowired
  12. private ApplicationContext appContext;
  13.  
  14. @Override
  15. protected String getDatabaseName() {
  16. return dbName;
  17. }
  18.  
  19. @Override
  20. public Mongo mongo() throws Exception {
  21. MongoClient mongoClient = new MongoClient(mongoHost, mongoPort);
  22. return mongoClient;
  23. }
  24.  
  25. @Override
  26. protected String getMappingBasePackage() {
  27. return MONGO_BASE_PACKAGE;
  28. }
  29.  
  30. @Override
  31. @Bean
  32. public MongoTemplate mongoTemplate() throws Exception {
  33. return new MongoTemplate(mongo(), getDatabaseName());
  34. }
  35. }

使用mongoTemplate操作

實體對象

  1. @Document(collection = "author")
  2. public class Author {
  3. @Id
  4. private Long id;
  5. private String realName;
  6. private String nickName;
  7. // SET和GET方法
  8. }

DAO相關

我們通過mongoTemplate進行數據訪問操作。

  1. @Repository
  2. public class AuthorDao {
  3. @Autowired
  4. private MongoTemplate mongoTemplate;
  5.  
  6. public void add(Author author) {
  7. this.mongoTemplate.insert(author);
  8. }
  9. public void update(Author author) {
  10. this.mongoTemplate.save(author);
  11. }
  12. public void delete(Long id) {
  13. Query query = new Query();
  14. query.addCriteria(Criteria.where("_id").is(id));
  15. this.mongoTemplate.remove(query, Author.class);
  16. }
  17. public Author findAuthor(Long id) {
  18. return this.mongoTemplate.findById(id, Author.class);
  19. }
  20. public List<Author> findAuthorList() {
  21. Query query = new Query();
  22. return this.mongoTemplate.find(query, Author.class);
  23. }
  24. }

Service相關

Service層調用Dao層的方法,這個是典型的套路。

  1. @Service
  2. public class AuthorService {
  3. @Autowired
  4. private AuthorDao authorDao;
  5.  
  6. public void add(Author author) {
  7. this.authorDao.add(author);
  8. }
  9. public void update(Author author) {
  10. this.authorDao.update(author);
  11. }
  12. public void delete(Long id) {
  13. this.authorDao.delete(id);
  14. }
  15. public Author findAuthor(Long id) {
  16. return this.authorDao.findAuthor(id);
  17. }
  18. public List<Author> findAuthorList() {
  19. return this.authorDao.findAuthorList();
  20. }
  21. }

Controller相關

為了展現效果,我們先定義一組簡單的 RESTful API 接口進行測試。

  1. @RestController
  2. @RequestMapping(value="/data/mongodb/author")
  3. public class AuthorController {
  4. @Autowired
  5. private AuthorService authorService;
  6. /**
  7. * 查詢用戶列表
  8. */
  9. @RequestMapping(method = RequestMethod.GET)
  10. public Map<String,Object> getAuthorList(HttpServletRequest request) {
  11. List<Author> authorList = this.authorService.findAuthorList();
  12. Map<String,Object> param = new HashMap<String,Object>();
  13. param.put("total", authorList.size());
  14. param.put("rows", authorList);
  15. return param;
  16. }
  17. /**
  18. * 查詢用戶信息
  19. */
  20. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
  21. public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
  22. Author author = this.authorService.findAuthor(userId);
  23. if(author == null){
  24. throw new RuntimeException("查詢錯誤");
  25. }
  26. return author;
  27. }
  28. /**
  29. * 新增方法
  30. */
  31. @RequestMapping(method = RequestMethod.POST)
  32. public void add(@RequestBody JSONObject jsonObject) {
  33. String userId = jsonObject.getString("user_id");
  34. String realName = jsonObject.getString("real_name");
  35. String nickName = jsonObject.getString("nick_name");
  36. Author author = new Author();
  37. if (author!=null) {
  38. author.setId(Long.valueOf(userId));
  39. }
  40. author.setRealName(realName);
  41. author.setNickName(nickName);
  42. try{
  43. this.authorService.add(author);
  44. }catch(Exception e){
  45. e.printStackTrace();
  46. throw new RuntimeException("新增錯誤");
  47. }
  48. }
  49. /**
  50. * 更新方法
  51. */
  52. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.PUT)
  53. public void update(@PathVariable Long userId, @RequestBody JSONObject jsonObject) {
  54. Author author = this.authorService.findAuthor(userId);
  55. String realName = jsonObject.getString("real_name");
  56. String nickName = jsonObject.getString("nick_name");
  57. author.setRealName(realName);
  58. author.setNickName(nickName);
  59. try{
  60. this.authorService.update(author);
  61. }catch(Exception e){
  62. e.printStackTrace();
  63. throw new RuntimeException("更新錯誤");
  64. }
  65. }
  66. /**
  67. * 刪除方法
  68. */
  69. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.DELETE)
  70. public void delete(@PathVariable Long userId) {
  71. try{
  72. this.authorService.delete(userId);
  73. }catch(Exception e){
  74. throw new RuntimeException("刪除錯誤");
  75. }
  76. }
  77. }

總結

上面這個簡單的案例,讓我們看到了 Spring Boot 整合 MongoDB 的整個流程。實際上,與 Spring 4 中 通過 Spring Data MongoDB 整合 MongoDB 是相同的, Spring Boot 默認集成了一些配置信息,但是個人更加偏向於方案二的手動創建方式,有更好的擴展性。

源代碼

相關示例完整代碼: springboot-action

(完)

 

微信公眾號


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM