数据库

 首页 > 数据库 > MongoDB > Spring Data MongoDB基础实例代码

Spring Data MongoDB基础实例代码

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

Spring Data MongoDB基础实例代码

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.运行效果

Spring Data MongoDB基础实例代码
分享到:
Java与MongoDB数据库编程
Java与MongoDB数据库编程 本周实验性地使用上mongodb,应用场景很简单,所以现在对mongodb了解也不是很深入。本文主要介绍mongodb的java客户端编程,这方面的内容也很简单,这里只是做个总结。不得不说,像mongodb这种介于kv和sql之间的存储,对很多的互联网应用很合适。mongodb现在的应用案例已经很多,并且社区的活跃度...
MongoDB高级聚合查询使用指南
MongoDB高级聚合查询使用指南 MongoDB版本为:2.0.8  系统为:64位Ubuntu 12.04 先给他家看一下我的表结构[Oh sorry, Mongo叫集合] 如你所见,我尽量的模拟现实生活中的场景。这是一个人的实体,他有基本的manId, manName, 有朋友[myFriends],有喜欢的水果[fruits],而且每种水果都有喜欢的权重。 很不好的...
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……