spring mvc mongodb

來源:互聯網
上載者:User
這裡參考一下文章: https://www.cnblogs.com/dennisit/p/3372568.html https://www.cnblogs.com/TinyBobo/p/7867208.html http://limingnihao.iteye.com/blog/1940446
建議大家看看第二個串連
首先引入jar檔案

mongo-java-driver-3.5.0.jar

spring-core-4.3.5.RELEASE.jar

spring-data-commons-1.13.9.RELEASE.jar

spring-data-commons-core-1.4.1.RELEASE.jar

spring-data-mongodb-1.8.4.RELEASE.jar
mongodb.properties
mongodb.host=資料庫ip地址
mongodb.port=27017
mongodb.connectionsPerHost=8
mongodb.threadsAllowedToBlockForConnectionMultiplier=4
mongodb.databasename=admin
mongo.user=使用者名稱
mongo.pwd=密碼
#
mongodb.connectTimeout=10000
mongodb.maxWaitTime=120000
mongodb.autoConnectRetry=true
mongodb.socketKeepAlive=true


mongodb.socketTimeout=0
mongodb.slaveOk=true


mongodb.writeNumber=1
mongodb.writeTimeout=0
mongodb.writeFsync=true

然後建立spring-mongo.xml <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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.xsd
http://www.springframework.org/schema/data/mongo    
        http://www.springframework.org/schema/data/mongo/spring-mongo-2.0.xsd
        http://www.springframework.org/schema/data/repository
    http://www.springframework.org/schema/data/repository/spring-repository-1.5.xsd
        http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd">
      
   <!--   <context:property-placeholder location="classpath:mongodb.properties"/> -->
      
      <mongo:mongo-client id="mongoClient" host="${mongodb.host}" port="${mongodb.port}" 
      credentials="${mongo.user}:${mongo.pwd}@${mongodb.databasename}">
      <!-- mongo串連屬性  -->
<mongo:client-options
connections-per-host="${mongodb.connectionsPerHost}"
threads-allowed-to-block-for-connection-multiplier="${mongodb.threadsAllowedToBlockForConnectionMultiplier}"
connect-timeout="${mongodb.connectTimeout}"
max-wait-time="${mongodb.maxWaitTime}"
socket-keep-alive="${mongodb.socketKeepAlive}"
socket-timeout="${mongodb.socketTimeout}"
/>           
      </mongo:mongo-client>
      <mongo:db-factory id="mongoDbFactory" dbname="${mongodb.databasename}" mongo-ref="mongoClient"/>
      
      <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoDbFactory" />
</bean>
      
          <!-- mongo傳回值實體類路徑 -->
     <mongo:mapping-converter base-package="com.ssm.model" />  
     <!-- 具體操作mongodb資料庫的方法檔案路徑 -->
  <mongo:repositories base-package="com.ssm.service.Impl"/>
 
   <context:annotation-config />  
      
</beans>

接著,要在spring.xml檔案中引入配置 <import resource="classpath*:config/spring-mongo.xml"/>

然後建立實體類 package com.ssm.model;


import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;




@Document(collection = "test")  //這裡test指表名
public class MongoTest {

   @Id  
private String id;


   private String title;


   private String description;


   private String by;
   
   private String url;


   private double likes;


public String getId() {
return id;
}


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


public String getTitle() {
return title;
}


public void setTitle(String title) {
this.title = title;
}


public String getDescription() {
return description;
}


public void setDescription(String description) {
this.description = description;
}


public String getBy() {
return by;
}


public void setBy(String by) {
this.by = by;
}


public double getLikes() {
return likes;
}


public void setLikes(double likes) {
this.likes = likes;
}


public String getUrl() {
return url;
}


public void setUrl(String url) {
this.url = url;
}
   
   
   


}
具體實作類別 package com.ssm.service.Impl;


import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import com.ssm.model.MongoTest;
import com.ssm.service.MongoService;


@Repository 
public class MongoServiceImpl implements MongoService {

@Autowired(required = false)
private MongoTemplate  mongoTemplate;
/**查詢所有日誌*/
public List<MongoTest> findAll(){
return mongoTemplate.findAll(MongoTest.class);
}
/**儲存日誌**/
public void save(MongoTest mongoTest){
mongoTemplate.save(mongoTest);
}
/**根據標題查詢日誌*/
public List<MongoTest> selectTitle(String title){
Query query=new Query(Criteria.where("title").is(title));
List<MongoTest> list=mongoTemplate.find(query, MongoTest.class);
return list;
}


}

實作類別介面 package com.ssm.service;


import java.util.List;


import com.ssm.model.MongoTest;


public interface MongoService {



List<MongoTest> findAll();


public void save(MongoTest t);


public List<MongoTest> selectTitle(String title);

}

這裡使用junit測試 package com.test;


import java.util.List;


import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


import com.alibaba.fastjson.JSONObject;
import com.ssm.model.MongoTest;
import com.ssm.service.MongoService;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:spring.xml","classpath*:spring-mybatis.xml","classpath:spring-mongo.xml"})
public class Test1 {

Logger logger=(Logger) Logger.getLogger(this.getClass());



@Autowired
MongoService mongoService;

//查詢所有日誌
@Test
public void getALl(){
List list=mongoService.findAll();


logger.info(JSONObject.toJSONString(list));
}
       //添加新日誌
@Test
public void save(){
MongoTest mongoTest=new MongoTest();
mongoTest.setTitle("日誌標題33");
mongoTest.setDescription("描述33");
mongoTest.setBy("來源33");
mongoTest.setUrl("www.fdfd.com33");
mongoTest.setLikes(400);
mongoService.save(mongoTest);




}
//根據標題查詢
@Test
public void getBy(){
String title="日誌標題3";
List<MongoTest> list=mongoService.selectTitle(title);
logger.info(JSONObject.toJSONString(list));
}


}
下面先測試儲存
貌似沒啥反應 看看資料庫
已經插入資料了 下面執行getALl(),查詢所有

接著測試條件查詢 @Test
public void getBy()

大功告成

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.