zoukankan      html  css  js  c++  java
  • Spring Boot 揭秘与实战(二) 数据存储篇

    文章目录

    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

    (完)

    微信公众号
  • 相关阅读:
    json
    [题解]luogu_P2151_HH去散步(矩阵floyd
    [题解]数字计数(数位dp(模板向
    【简单计数知识】JZOJ6395. 【NOIP2019模拟2019.10.28】消失的序列
    字符云例子
    JAVA FileUtils(文件读写以及操作工具类)
    AT2657 Mole and Abandoned Mine
    Problem: [Usaco2018 Open]Team Tic Tac Toe
    Problem: [USACO2018 Jan]Blocked Billboard II
    算法——星星树
  • 原文地址:https://www.cnblogs.com/cnblog-long/p/7238851.html
Copyright © 2011-2022 走看看