spring 访问 mongo

2017-06-25

70

0

技术:spring-data-mongodb 1.10.1.RELEASE + mongo3.2.10

运行环境:IDEA 15.2 + jdk8 + windows 10

demo功能:提供一个使用spring访问mongo的demo代码

新建mongo访问MongoDao.java

import com.demoworld.entity.HelloKitty;
import com.mongodb.Mongo;
import com.mongodb.WriteResult;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import java.net.UnknownHostException;

/**
 * Created by francis on 2017/6/25.
 */
public class MongoDao {
    public MongoDao() {
        Mongo mongo= null;
        try {
            mongo = new Mongo("127.0.0.1", 27017);//mongo所在ip和端口号
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        mongoTemplate = new MongoTemplate(mongo, "db_dev");//操作的数据库
    }
    private static String HELLOKITTY = "hellokitty";//操作的文档集合, 相当于表
    private MongoTemplate mongoTemplate;
    public void createHelloKitty(HelloKitty hello) {
        mongoTemplate.insert(hello, HELLOKITTY);
    }
    public HelloKitty getHelloKittyByName(String name) {
        return mongoTemplate.findOne(new Query(Criteria.where("name").is(name)), HelloKitty.class, HELLOKITTY);
    }
    public int deleteByName(String name){
        WriteResult er=  mongoTemplate.remove(new Query(Criteria.where("name").is(name)), HelloKitty.class, HELLOKITTY);
        return er.getN();
    }
}

新建数据库实体类 HelloKitty.java

public class HelloKitty {
    private String id;
    private String name;
    private int age;
    public String getId() {        return id;    }
    public void setId(String id) {        this.id = id;    }
    public String getName() {        return name;    }
    public void setName(String name) {        this.name = name;    }
    public int getAge() {        return age;    }
    public void setAge(int age) {this.age = age;}
}

测试类, 很多操作参考 

http://www.cnblogs.com/xusir/archive/2012/12/24/2830957.html

@Test
public void add() {
    HelloKitty input = new HelloKitty();
    input.setName("francis");
    input.setAge(16);
    input.setId(UUID.randomUUID().toString());
    new MongoDao().createHelloKitty(input);
}

@Test
public void get() {
    HelloKitty tmpResult =  new MongoDao().getHelloKittyByName("francis");
    System.out.println(tmpResult.getId());
}

@Test
public void delete() {
    int n =  new MongoDao().deleteByName("francis");
    System.out.println(n);
}

测试结果

> show dbs#查询当前mongo有多少个数据库
db_dev 0.000GB
local 0.000GB
>
> use db_dev#使用其中一个库
switched to db db_dev
>
> show tables#查看有哪些表
hellokitty
> db.hellokitty.find()#添加前查看数据, 没有
> db.hellokitty.find()#添加后, 查看数据,确认是否添加成功
{ "_id" : "d5d1b3d4-0f34-4647-9e56-2a2933cdec3e", "_class" : "com.demoworld.entity.HelloKitty", "name" : "francis", "age" : 16 }
>

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think