我的漫漫程序之旅

专注于JavaWeb开发
随笔 - 37, 文章 - 309, 评论 - 411, 引用 - 0
数据加载中……

Spring mongodb 之简单CRUD

官方文档参考:http://www.mkyong.com/mongodb/  
用MyEclipse添加maven-Project工程,在这之前你可能需要配置你的m2eclipse
1.将maven配置成你自己安装的版本。


2.设置User Settings
当然也可以修改仓库默认目录,打maven安装目录conf/setting.xml
在<settings>节点里
添加:<localRepository>d:/myrepository</localRepository>即可


pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.test</groupId>
  <artifactId>mongodb</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>springmongodb</name>
  <description>This is test case</description>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  
  <repositories>
        <repository>
            <id>spring-milestone</id>
            <name>Spring Maven MILESTONE Repository</name>
            <url>http://maven.springframework.org/milestone</url>
        </repository>
    </repositories>
 
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>
 
        <!-- Spring framework -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
 
        <!-- mongodb java driver -->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.5.2</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.0.0.M2</version>
        </dependency>
 
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>
 
    </dependencies>
    
</project>
写完pom.xml后,执行 项目-右键-run-maven install 
下载完jar包,Test 成功后,就可以写代码了。
SpringMongoConfig.java
package com.config;

import org.springframework.context.annotation.Bean;
import org.springframework.data.document.mongodb.MongoTemplate;
import org.springframework.data.document.mongodb.config.AbstractMongoConfiguration;

import com.mongodb.Mongo;

public class SpringMongoConfig extends AbstractMongoConfiguration
{
    //主机
    @Override
    public Mongo mongo() throws Exception {
        return new Mongo("localhost");
    }
    //数据库
    @Override
    public @Bean MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongo(), "test");
    }

}
实体类:
package entity;

import java.util.List;

public class User
{

    private String id;
    private String username;
    private String password;
    //文档中的集合
    private List<String> position;

    // 要有声明默认的构造方法,不然查询的时候会报错(无法实例化)
    public User()
    {

    }

    public String getId()
    {
        return id;
    }

    public void setId(String id)
    {
        this.id = id;
    }

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    public List<String> getPosition()
    {
        return position;
    }

    public void setPosition(List<String> position)
    {
        this.position = position;
    }

    public User(String id, String username, String password,
            List<String> position)
    {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.position = position;
    }

    public User(String username, String password, List<String> position)
    {
        super();
        this.username = username;
        this.password = password;
        this.position = position;
    }

}
测试类:
package run;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
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.config.SpringMongoConfig;

import entity.User;

public class App
{
    private ApplicationContext ctx = new AnnotationConfigApplicationContext(
            SpringMongoConfig.class);
    private MongoOperations mongoOperations = (MongoOperations) ctx
            .getBean("mongoTemplate");

    @Test
    public void testSave()
    {
        List<String> list = new ArrayList<String>();
        for(int i =0; i < 100; i ++)
        {
            list.add("开发" + i);
            list.add("经理" + i);
            User user = new User("John" + i,"123" + i,list);
            //第一个参数:要保存的表名,默认为实例名user同名的集合(表)
            
//如果表不存在会自动创建, 表名user为关键字不要使用
            mongoOperations.save("userinfo", user);
            list.clear();
        }
    }

    @Test
    public void testUpdate()
    {
        mongoOperations.updateFirst("userinfo",
                new Query(Criteria.where("username").is("John0")),
                Update.update("password", "newpassword"));
    }

    @Test
    public void testDelete()
    {
        mongoOperations.remove("userinfo",new Query(Criteria.where("id").is("4ffe3486b41f8ed41269a729")),User.class);
    }

    @Test
    public void testQuery()
    {
        //输出所有表名
        Set<String> set = mongoOperations.getCollectionNames();
        Iterator<String> it =  set.iterator();
        while(it.hasNext())
        {
            System.out.println(it.next());
        }
        //user:要查询的表名
        List<User> users = mongoOperations.getCollection("userinfo", User.class);
        System.out.println(users.size());
        for(User u : users)
        {
            System.out.println(u.getId());
        }
    }

}

源码下载

posted on 2012-07-12 10:42 々上善若水々 阅读(4630) 评论(0)  编辑  收藏 所属分类: 数据库


只有注册用户登录后才能发表评论。


网站导航: