kution 发表于 2017-12-14 23:40:25

Spring 与 mongoDB 整合

  首先需要引入jar包

  

<dependency>  
   <groupId>org.mongodb</groupId>
  
   <artifactId>mongodb-driver</artifactId>
  
   <version>3.3.0</version>
  
</dependency>
  
<dependency>
  
   <groupId>org.springframework.data</groupId>
  
   <artifactId>spring-data-mongodb</artifactId>
  
   <version>1.9.4.RELEASE</version>
  
</dependency>
  


View Code  spring中注入对象org.springframework.data.mongodb.core.MongoTemplate,该类中包含了mongoDB的增删改查

  

<!-- MongoDB -->  
<mongo:mongo-client host="${mongo.host}"
  
         port="${mongo.port}" credentials="${mongo.credentials}">
  
   <mongo:client-options write-concern="NORMAL" />
  
</mongo:mongo-client>
  
   
  
<bean>
  
   <constructor-arg ref="mongo-client" />
  
   <constructor-arg name="databaseName" value="${mongo.databaseName}" />
  
</bean>
  


View Code  需要注意的是:
  host:主机ip
  port:端口号
  credentials:连接mongoDB的一些参数,规则如:“username:password@Authentication”  
  如果用的是MongoChef可视化工具,对应如下所示的三个参数。

  首先需要引入mongo对象,
  

@Autowired  

private MongoOperations mongo;  

  删除操作

  

@Override  

   public void deleteQstByTpId(String tpId) {  

         mongo.remove(new Query(Criteria.where("test").is(tpId)),QuestionBean.class,COLLECTION_NAME);  

   }  


View Code  增加操作

  

@Override  

   public void insertListZzQst(List<QuestionBean> list) {  

         mongo.insert(list,COLLECTION_NAME);  

   }  


View Code  查找操作

  

@Override  

   public List<QuestionBean> findAllQstByTpId(String tpId) {  

         List<QuestionBean> list = mongo.find(new Query(Criteria.where("test").is(tpId)), QuestionBean.class,COLLECTION_NAME);  

         return list;  

   }  


View Code  多条件查询

  

@Override  

   public List<QuestionBean> qrySomeQst(List<String> qryList,String testPaperId) {  

         return mongo.find(new Query(Criteria.where("test").is(testPaperId).andOperator(Criteria.where("type").in(qryList))), QuestionBean.class,COLLECTION_NAME);  

   }  


View Code
页: [1]
查看完整版本: Spring 与 mongoDB 整合