官网:https://spring.io/projects/spring-data-mongodb
基本使用
1、配置Maven依赖,与Spring Framework版本要匹配
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
3、实体类 POJO
public class Person {
private String id;
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
3、使用
MongoOperations mongoOps = new MongoTemplate(new MongoClient("localhost", 27017), "test"); // 连接仓库
mongoOps.insert(new Person("Joe", 34), "collection1"); // 往集合collection1插入数据
mongoOps.insert(new Person("Joe", 34)); // 不指定集合,那么集合为插入对象的类名小写化,即person
System.out.println(mongoOps.findOne(new Query(where("name").is("Joe")), Person.class)); // 从person集合里查找
mongoOps.remove(new Query().limit(3), "person"); // 从person集合里删除3条文档
mongoOps.upsert(new Query(), new Update("address", "新地址"), Person.class); // 更新数据
容器使用
1、Spring 容器配置
需引入命名空间
<mongo:mongo-client host="localhost" port="27017"> <!-- 指定IP,端口,可以是mongod也可以说mongos -->
<mongo:client-options connections-per-host="8"
threads-allowed-to-block-for-connection-multiplier="4"
connect-timeout="1000"
max-wait-time="1500"
socket-keep-alive="true"
socket-timeout="1500"/>
</mongo:mongo-client>
<mongo:db-factory dbname="test" mongo-ref="mongoClient"/> <!-- 指定仓库 -->
<bean id="anotherMongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
2、使用
@Autowired
private MongoOperations mongoOps;
mongoOps.insert(new Person("Joe", 34));
System.out.println(mongoOps.findOne(new Query(where("name").is("Joe")), Person.class));
网友评论