设为首页 收藏本站
查看: 1090|回复: 0

[经验分享] Spring Boot 揭秘与实战(二) 数据存储篇

[复制链接]

尚未签到

发表于 2017-12-16 13:17:01 | 显示全部楼层 |阅读模式
  文章目录

  • 1. 环境依赖
  • 2. 数据源

    • 2.1. 方案一 使用 Spring Boot 默认配置
    • 2.2. 方案二 手动创建

  • 3. 使用mongoTemplate操作4. 总结

    • 3.1. 实体对象
    • 3.2. DAO相关
    • 3.3. Service相关
    • 3.4. Controller相关


  • 5. 源代码
  本文讲解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>

  • 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>
  • @Id
  • private Long>
  • private String realName;
  • private String nickName;
  • // SET和GET方法
  • }
DAO相关
  我们通过mongoTemplate进行数据访问操作。

  • @Repository
  • public>
  • @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>
  • Query query = new Query();
  • query.addCriteria(Criteria.where("_id").is(id));
  • this.mongoTemplate.remove(query, Author.class);
  • }
  • public Author findAuthor(Long>
  • 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>
  • @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>
  • this.authorDao.delete(id);
  • }
  • public Author findAuthor(Long>
  • return this.authorDao.findAuthor(id);
  • }
  • public List<Author> findAuthorList() {
  • return this.authorDao.findAuthorList();
  • }
  • }
Controller相关
  为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。

  • @RestController
  • @RequestMapping(value="/data/mongodb/author")
  • public>
  • @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
  (完)
  如果觉得我的文章对你有帮助,请随意打赏。

DSC0000.png

  • 版权声明:本文由 梁桂钊 发表于 梁桂钊的博客
  • 转载声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证),非商业转载请注明作者及出处,商业转载请联系作者本人。
  • 文章标题:Spring Boot 揭秘与实战(二) 数据存储篇 - MongoDB
  • 文章链接:http://blog.720ui.com/2016/springboot_02_data_mongodb/

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-424693-1-1.html 上篇帖子: Spark With Mongodb 实现方法及error code 下篇帖子: Java spring-mongodb获取指定字段的值
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表