Pom 引用
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-mongodb -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.10.4.RELEASE</version>
</dependency>
mongo.properties
mongo.dbname=test
mongo.host=localhost
mongo.port=27017
mongo.connectionsPerHost=8
mongo.threadsAllowedToBlockForConnectionMultiplier=4
mongo.connectTimeout=1500
mongo.maxWaitTime=1500
mongo.autoConnectRetry=true
mongo.socketKeepAlive= true
mongo.socketTimeout=1500
mongo.slaveOk=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"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.7.xsd
http://www.springframework.org/schema/data/repository
http://www.springframework.org/schema/data/repository/spring-repository-1.7.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.2.xsd"
default-lazy-init="default">
<!--credentials的配置形式是:用户名:密码@默认数据库-->
<mongo:mongo-client id="mongoClient" host="${mongo.host}" port="${mongo.port}" >
<mongo:client-options write-concern="SAFE"
connections-per-host="${mongo.connectionsPerHost}"
threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
connect-timeout="${mongo.connectTimeout}"
max-wait-time="${mongo.maxWaitTime}"
socket-timeout="${mongo.socketTimeout}"/>
</mongo:mongo-client>
<mongo:db-factory id="mongoDbFactory" dbname="${mongo.dbname}" mongo-ref="mongoClient" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
</beans>
spring-context.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:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="configRealm"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:mongo.properties</value>
</list>
</property>
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configRealm" />
</bean>
<import resource="spring-mongo.xml" />
</beans>
Food 实体类, mapping MongoDb中的collection
package com.test;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
@Document(collection = "foods")
public class Food {
@PersistenceConstructor
public Food(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
@Id
private String _objectId;
@Field("id")
private int id;
private String name;
private double price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String get_objectId() {
return _objectId;
}
public void set_objectId(String _objectId) {
this._objectId = _objectId;
}
@Override
public String toString() {
return String.format("{Id:%s , Name:%s , Price:%s}", id, name, price);
}
}
测试类
package com.test;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
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.data.mongodb.core.query.Update;
//http://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/query
public class Main {
static MongoTemplate mongoTemplate = null;
static {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
mongoTemplate = (MongoTemplate) context.getBean("mongoTemplate");
}
public static void main(String[] args) {
// test_Update();
// test_Delete();
test_Find();
}
/**
* add some test data
*/
static void initSome() {
List<Food> foods = new ArrayList<Food>(10);
String[] names = { "rice", "bread", "milk", "egg", "potato", "tomato", "banana", "orange", "cake", "canddy" };
double[] prices = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 };
for (int i = 0; i < 10; i++) {
Food food = new Food(i + 1, names[i], prices[i]);
foods.add(food);
}
mongoTemplate.insertAll(foods);
}
/**
* clean all the data in foods
*/
static void cleanFoods() {
mongoTemplate.findAllAndRemove(new Query(), Food.class);
}
static void test_Update() {
cleanFoods();
initSome();
Criteria criteria = new Criteria("id");
criteria.is(1);
Query query = new Query(criteria);
System.out.println("Before update:");
System.out.println(mongoTemplate.find(query, Food.class));
Update update = new Update();
update.set("price", 100);
mongoTemplate.updateFirst(query, update, Food.class);
System.out.println("After update:");
System.out.println(mongoTemplate.find(query, Food.class));
}
static void test_Delete() {
cleanFoods();
initSome();
Criteria criteria = new Criteria("id");
criteria.is(1);
Query query = new Query(criteria);
System.out.println("Before delete count:");
System.out.println(mongoTemplate.count(new Query(), Food.class));
mongoTemplate.findAllAndRemove(query, Food.class);
System.out.println("After delete count:");
System.out.println(mongoTemplate.count(new Query(), Food.class));
}
static void test_Find() {
cleanFoods();
initSome();
// where price=5
// Criteria criteriaDefinition = new Criteria("price");
// criteriaDefinition.is(5);
// Query query = new Query(criteriaDefinition);
// System.out.println(mongoTemplate.find(query, Food.class));
// where price <5
// Criteria criteriaDefinition = new Criteria("price");
// criteriaDefinition.lt(5);
// Query query = new Query(criteriaDefinition);
// System.out.println(mongoTemplate.find(query, Food.class));
// where price <=5
// Criteria criteriaDefinition = new Criteria("price");
// criteriaDefinition.lte(5);
// Query query = new Query(criteriaDefinition);
// System.out.println(mongoTemplate.find(query, Food.class));
// where price >5
// Criteria criteriaDefinition = new Criteria("price");
// criteriaDefinition.gt(5);
// Query query = new Query(criteriaDefinition);
// System.out.println(mongoTemplate.find(query, Food.class));
// where price >=5
// Criteria criteriaDefinition = new Criteria("price");
// criteriaDefinition.gte(5);
// Query query = new Query(criteriaDefinition);
// System.out.println(mongoTemplate.find(query, Food.class));
// where price !=5
// Criteria criteriaDefinition = new Criteria("price");
// criteriaDefinition.ne(5);
// Query query = new Query(criteriaDefinition);
// System.out.println(mongoTemplate.find(query, Food.class));
// where price =9 and id>8
// Criteria criteriaDefinition_price = new Criteria("price");
// criteriaDefinition_price.is(9);
//
// Criteria criteriaDefinition_Id = new Criteria("id");
// criteriaDefinition_Id.gt(8);
//
// Criteria criteriaDefinition_and = new Criteria();
// criteriaDefinition_and.andOperator(criteriaDefinition_price,criteriaDefinition_Id);
//
// Query query = new Query(criteriaDefinition_and);
// System.out.println(mongoTemplate.find(query, Food.class));
// where price>5 or name=rice
// Criteria criteriaDefinition_price = new Criteria("price");
// criteriaDefinition_price.gt(9);
//
// Criteria criteriaDefinition_name = new Criteria("name");
// criteriaDefinition_name.is("rice");
//
// Criteria criteria_or = new Criteria();
// criteria_or.orOperator(criteriaDefinition_price,criteriaDefinition_name);
//
// Query query = new Query(criteria_or);
// System.out.println(mongoTemplate.find(query, Food.class));
// where (price>5 or name=rice) and id>8
// Criteria criteriaDefinition_price = new Criteria("price");
// criteriaDefinition_price.gt(9);
//
// Criteria criteriaDefinition_name = new Criteria("name");
// criteriaDefinition_name.is("rice");
//
// Criteria criteria_or = new Criteria();
// criteria_or.orOperator(criteriaDefinition_price,
// criteriaDefinition_name);
//
// Criteria criteriaDefinition_id = new Criteria("id");
// criteriaDefinition_id.gt(8);
//
// Criteria criteria_and = new Criteria();
// criteria_and.andOperator(criteria_or, criteriaDefinition_id);
//
// Query query = new Query(criteria_and);
// System.out.println(mongoTemplate.find(query, Food.class));
// where name in ('bread','cake')
// Criteria criteriaDefinition = new Criteria("name");
// criteriaDefinition.in(Arrays.asList("bread", "cake"));
// Query query = new Query(criteriaDefinition);
// System.out.println(mongoTemplate.find(query, Food.class));
// order by id desc
// Order order = new Order(Sort.Direction.DESC, "id");
// Sort sort = new Sort(order);
// Query query = new Query();
// query.with(sort);
// System.out.println(mongoTemplate.find(query, Food.class));
// limit 3
Pageable pageable = new PageRequest(1, 3);
Query query = new Query();
query.with(pageable);
System.out.println(mongoTemplate.find(query, Food.class));
}
}