Java学习笔记程序员

当Spring遇见MongoDB,十分钟搞定CRUD

2017-02-17  本文已影响161人  Vantiboolean
1.引入相关依赖 使用maven引入
<dependencies> 
  <dependency> 
    <groupId>junit</groupId> 
    <artifactId>junit</artifactId> 
    <version>4.11</version> 
  </dependency> 
  <dependency>
    <groupId>ch.qos.logback</groupId> 
    <artifactId>logback-classic</artifactId> 
    <version>1.1.1</version> 
  </dependency> 
  <dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-context</artifactId>
     <version>4.3.4.RELEASE</version>
   </dependency> 
  <dependency> 
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId> 
    <version>1.9.5.RELEASE</version> 
  </dependency> 
</dependencies>
2.配置MongoDB连接

spring官网提供了很多种配置方式 spring-mongo-reference
这是其中一种

import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.data.mongodb.core.MongoClientFactoryBean; 
import org.springframework.data.mongodb.core.MongoOperations; 
import org.springframework.data.mongodb.core.MongoTemplate; 
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; 
import com.mongodb.Mongo; 
@Configuration 
public class MongoConfig 
{
  @Bean 
  public MongoClientFactoryBean mongo(){ 
      MongoClientFactoryBean factoryBean = new MongoClientFactoryBean();        
      factoryBean.setHost("localhost"); // 数据库地址 
      factoryBean.setPort(27017); // 端口 
      return factoryBean; 
  } 
  @Bean 
  public MongoOperations mongoTemplate(Mongo mongo)\
  { 
  // 操作Mongo的模板类,提供了非常纯粹的oo操作数据库的api 
  return new MongoTemplate(mongo, "dbtest"); // dbtest 为数据库名 
  } 
}
3.编写测试类
public class Person 
{ 
    private String id; 
    private String name; 
    private int age; 

    public Person(String name, int age) { 
          this.name = name; 
          this.age = age; 
    } 
    public String getId() { 
          return id; 
    } 
    public String getName() { 
          return name; 
    } 
    public int getAge() { 
          return age; 
    } 
    @Override 
    public String toString() { 
          return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";   
    } 
}

(1)insert

@Test 
public void insert() 
{ 
  AnnotationConfigApplicationContext a = new AnnotationConfigApplicationContext( MongoConfig.class);   
  MongoOperations mongoOps = a.getBean(MongoOperations.class); 
  Person person = new Person("white", 23);
  // 单条插入 
  mongoOps.insert(person); 
  List<Person> persons = new ArrayList<Person>(); 
  for (int i = 1; i <= 20; i++) { 
      persons.add(new Person("white" + i + "号", 20 + i)); 
  } 
  // 批量插入 
  mongoOps.insertAll(persons); 
  a.close(); 
}

一行代码搞定了Mongo的插入操作,这里我们并没有设置Mongo的集合名,只是传入了一个实体对象,初步猜想MongoOperations 模板类应该是把实体类的类名或者全类名作为了集合的名称,这里MongoOperations 把类名小写之后作为了Mongo集合的名称,而把当前类的全类名作为了一个字段存储到了数据库中。

(2)query
为了方便操作
// 静态导入
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Update.update;

@Test 
public void query() 
{ 
    AnnotationConfigApplicationContext a = new AnnotationConfigApplicationContext( MongoConfig.class); 
    MongoOperations mongoOps = a.getBean(MongoOperations.class); 
    
    // 查询匹配条件的第一条数据 
    Person findOne = mongoOps.findOne(new Query(where("name").is("white")), Person.class);     
    System.out.println(findOne); 
    
    // 查询所有记录 
    List<Person> all = mongoOps.findAll(Person.class); 
    System.out.println(all); 
    
    // 查询age >= 25 and age < 30 
    Query query = new Query(where("age").gte(25).lt(30)); 
    List<Person> findByCondition = mongoOps.find(query , Person.class);   
    System.out.println(findByCondition); 
    
    // 原生命令方式 
    BasicQuery bq =new BasicQuery("{name:'white'}");   
    Person findOne2 = mongoOps.findOne(bq, Person.class); 
    System.out.println(findOne2); a.close(); 
}

(3)delete

@Test 
public void delete() 
{ 
    AnnotationConfigApplicationContext a = new AnnotationConfigApplicationContext( MongoConfig.class); 
    MongoOperations mongoOps = a.getBean(MongoOperations.class); 
    
    // 删除age>=25的所有记录 
    WriteResult remove = mongoOps.remove(new Query(where("age").gte(25)),Person.class); 

    // 查出第一条匹配的记录并把这条记录删除 阅后即焚 
    Person findAndRemove = mongoOps.findAndRemove(new Query(where("name").is("white")), Person.class); 
    System.out.println(findAndRemove); 
    
    // 按对象删除 
    Person p = mongoOps.findOne(new Query(where("age").is(22)), Person.class); 
    mongoOps.remove(p); 
    
    // 删除集合 
    mongoOps.dropCollection(Person.class); 
    a.close(); 
}

(4)update

@Test 
public void updateTest() 
{ 
    AnnotationConfigApplicationContext a = new AnnotationConfigApplicationContext( MongoConfig.class); 
    MongoOperations mongoOps = a.getBean(MongoOperations.class); 

    // 更新一条 
    mongoOps.updateFirst(new Query(where("age").is(23)), update("name","white小哥"), Person.class); 
    
    // 更新多条 
    mongoOps.updateMulti(new Query(where("age").lte(23)), update("name","white大哥"), Person.class); 
    a.close();
}
上一篇下一篇

猜你喜欢

热点阅读