其實,之前項目組也使用過mongodb,只是那時候是做爲主數據庫來使用,因此在框架方面會更加複雜,好比使用jpa,若是隻是把mongodb做爲附數據庫使用的話,我的認爲經過spring-data-mongodb的mongoTemple來操做數據庫便可。java
<?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-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <mongo:mongo host="192.168.5.117" port="27017" /> <bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate"> <constructor-arg name="mongo" ref="mongo" /> <constructor-arg name="databaseName" value="xxx-log" /> <constructor-arg name="defaultCollectionName" value="log" /> </bean> </beans>
以下,關鍵是要另外配置maven倉庫,由於這裏mongodb是多爲日誌記錄,因此其實並不但願對實體進行映射,若是可以作到經過簡單實體就可以跟mongo對應就行了,在這方面spring-data-mongodb的1.0.0.M2版本能夠實現,而此版本在中央倉庫是沒有的。web
<repositories> <repository> <id>spring-milestone</id> <name>Spring Maven MILESTONE Repository</name> <url>http://maven.springframework.org/milestone</url> </repository> </repositories> <dependencies> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>${version.spring.data}</version> </dependency> <!-- 本地jar --> <dependency> <groupId>com.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.12.1</version> <scope>system</scope> <systemPath>${basedir}/src/main/webapp/WEB-INF/lib/mongo-java-driver-2.12.1.jar</systemPath> </dependency> </dependencies>
@Test public void testAdd() { ApplicationContext ctx = new GenericXmlApplicationContext( "classpath*:applicationContext-mongo.xml"); mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate"); LogVo logVo = new LogVo(); logVo.setUserName("15920564512"); mongoLogService.save(logVo); Query logQuery = new Query(Criteria.where("userName").is("15920564512")); logVo = mongoOperation.findOne("log", logQuery, LogVo.class); Assert.assertNotNull(logVo); }