热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

SpringDataMongoDB基础实例代码

1.以下从官方下载示例,下载地址如下所示:http://www.springsource.org/samples2.排错,刚下载下来的SpringExample有错误,首先它不是一个maven项目,单击右键使其转换成maven项目,添加一些依赖,比如spring-aop,spring-context,spring-co

1.以下从官方下载示例,下载地址如下所示:

http://www.springsource.org/samples

2.排错,

   刚下载下来的SpringExample有错误,首先它不是一个maven项目,单击右键使其转换成maven项目,添加一些依赖,比如spring-aop,spring-context,spring-core,log4j等依赖。同时更新你的依赖包,依赖配置,最终运行成功后,运行下一步。

3.代码讲解。

3.1  方式一(注解方式开启mongo.exe,同时创建数据库yourdb,文档yourCollection),代码如下所示:

package com.mkyong.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.document.mongodb.MongoTemplate;
import org.springframework.data.document.mongodb.config.AbstractMongoConfiguration;
import com.mongodb.Mongo;
/**
 * Spring MongoDB configuration file
 *
 */
@Configuration
public class SpringMongoConfig extends AbstractMongoConfiguration {
        @Override
        public @Bean Mongo mongo() throws Exception {
                return new Mongo("localhost");
        }
        @Override
        public @Bean MongoTemplate mongoTemplate() throws Exception {
                return new MongoTemplate(mongo(),"yourdb","yourCollection");
        }
}


3.2方式二(配置文件的方式),代码如下所示:



        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cOntext="http://www.springframework.org/schema/context"
        xmlns:mOngo="http://www.springframework.org/schema/data/mongo"
        xsi:schemaLocation="http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/data/mongo
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
        
        
        
                
                
                
        
        
        

3.3 实体类的编写

package com.mkyong.user;
public class User {
        private String id;
        private String firstname;
        private String lastname;
        private int age;
        public User(){};
        public User(String id, String firstname, String lastname, int age) {
                super();
                this.id = id;
                this.firstname = firstname;
                this.lastname = lastname;
                this.age = age;
        }
        public String getId() {
                return id;
        }
        public void setId(String id) {
                this.id = id;
        }
        public String getFirstname() {
                return firstname;
        }
        public void setFirstname(String firstname) {
                this.firstname = firstname;
        }
        public String getLastname() {
                return lastname;
        }
        public void setLastname(String lastname) {
                this.lastname = lastname;
        }
        public int getAge() {
                return age;
        }
        public void setAge(int age) {
                this.age = age;
        }
        @Override
        public String toString() {
                return "User [id=" + id + ", firstname=" + firstname + ", lastname="
                                + lastname + ", age=" + age + "]";
        }
}

最后书写main类,如下所示:

package com.mkyong.core;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.data.document.mongodb.MongoOperations;
import org.springframework.data.document.mongodb.query.Criteria;
import org.springframework.data.document.mongodb.query.Query;
import org.springframework.data.document.mongodb.query.Update;
import com.mkyong.config.SpringMongoConfig;
import com.mkyong.user.User;
public class App
{
    public static void main( String[] args )
    {
        //For Annotation 注解方式
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
        //For XML XML配置文件方式
        //ApplicationContext ctx = new GenericXmlApplicationContext("mongo-config.xml");
        MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");
        User user = new User("1001", "yong", "mook kim", 30);
        //save
        mongoOperation.save("userprofile",user);
        //find
        User savedUser = mongoOperation.findOne("userprofile",
                        new Query(Criteria.where("id").is("1001")),
                                User.class);
        System.out.println("savedUser : " + savedUser);
        //update
        mongoOperation.updateFirst("userprofile",
                        new Query(Criteria.where("firstname").is("yong")),
                        Update.update("lastname", "new lastname"));
        //find
        User updatedUser = mongoOperation.findOne(
                        "userprofile",
                        new Query(Criteria.where("id").is("1001")),
                                User.class);
        System.out.println("updatedUser : " + updatedUser);
        //delete
        mongoOperation.remove("userprofile",
                        new Query(Criteria.where("id").is("1001")),
                        User.class);
        //List
        List listUser =
                mongoOperation.getCollection("userprofile", User.class);
        System.out.println("Number of user = " + listUser.size());
    }
}


 由于只是一些CURD的操作,比较简单,直接看代码就明白了,我就不多讲了。


4.运行效果


推荐阅读
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
  • Android开发实现的计时器功能示例
    本文分享了Android开发实现的计时器功能示例,包括效果图、布局和按钮的使用。通过使用Chronometer控件,可以实现计时器功能。该示例适用于Android平台,供开发者参考。 ... [详细]
  • Linux如何安装Mongodb的详细步骤和注意事项
    本文介绍了Linux如何安装Mongodb的详细步骤和注意事项,同时介绍了Mongodb的特点和优势。Mongodb是一个开源的数据库,适用于各种规模的企业和各类应用程序。它具有灵活的数据模式和高性能的数据读写操作,能够提高企业的敏捷性和可扩展性。文章还提供了Mongodb的下载安装包地址。 ... [详细]
  • MongoDB用户验证auth的权限设置及角色说明
    本文介绍了MongoDB用户验证auth的权限设置,包括readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase、cluster相关的权限以及root权限等角色的说明和使用方法。 ... [详细]
  • Allegro总结:1.防焊层(SolderMask):又称绿油层,PCB非布线层,用于制成丝网印板,将不需要焊接的地方涂上防焊剂.在防焊层上预留的焊盘大小要比实际的焊盘大一些,其差值一般 ... [详细]
  • step1.为mongodb添加admin管理员root@12.154.29.163:~#mongoMongoDBshellversionv3.4.2connectingto:mo ... [详细]
  • 一、前言在数据库中,慢查询日志通常是用来进行优化数据库,MySQL中存在慢查询,Mongodb中也是如此。在Mongo中的慢查询属于Mon ... [详细]
  • Abp+MongoDb改造默认的审计日志存储位置
    一、背景在实际项目的开发当中,使用AbpZero自带的审计日志功能写入效率比较低。其次审计日志数据量中后期十分庞大,不适合与业务数据存放在一起。所以我们可以重新实现A ... [详细]
  • 今天我们学习,数据库mongodb的使用,最下面有mongodb的下载链接。pipinstallpymongo首先安装pymongo,然后在需要用到的地方importpymongo ... [详细]
  • MongoDB学习:(二)MongoDB简单使用
    MongoDB学习:(二)MongoDB简单使用MongoDB使用:执行mongodb的操作之前,我们需要运行命令,来进入操作命令界面>mongo提示 ... [详细]
  •     系统采用jeeplus框架(ssm+redis+shiro+mongodb+redis),默认是做了JSP未做前后端分离,由于业务需要已经多终端使用的需求(H5、小程序等) ... [详细]
  • 本文介绍了Java工具类库Hutool,该工具包封装了对文件、流、加密解密、转码、正则、线程、XML等JDK方法的封装,并提供了各种Util工具类。同时,还介绍了Hutool的组件,包括动态代理、布隆过滤、缓存、定时任务等功能。该工具包可以简化Java代码,提高开发效率。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文讲述了如何通过代码在Android中更改Recycler视图项的背景颜色。通过在onBindViewHolder方法中设置条件判断,可以实现根据条件改变背景颜色的效果。同时,还介绍了如何修改底部边框颜色以及提供了RecyclerView Fragment layout.xml和项目布局文件的示例代码。 ... [详细]
author-avatar
书友74972801
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有