# SpringData-mongdb
**Repository Path**: kshjit/SpringData-mongdb
## Basic Information
- **Project Name**: SpringData-mongdb
- **Description**: 🐱 idea 搭建 springdata+mongodb+maven+springmvc 工程。
- **Primary Language**: Java
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 1
- **Forks**: 0
- **Created**: 2020-09-21
- **Last Updated**: 2023-06-16
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# idea搭建springdata+mongodb+maven+springmvc
今天我们来学习一下SpringData操作MongoDB。
项目环境:IntelliJ IDEA2017+maven3.5.0+MongoDB 3.2+JDK1.7+spring4.3.8
推荐网站(适合学习各种知识的基础):[http://www.runoob.com/](http://www.runoob.com/)
mongo安装请参考:http://www.runoob.com/mongodb/mongodb-window-install.html
## **1. 创建maven工程**
首相创建maven工程,New project:


这里不使用idea自带maven插件,改用下载好的3.5.0版maven;
由于最近osChina的maven仓库挂掉,推荐大家使用阿里的镜像,速度快的飞起
`maven`配置:`D:\apache-maven-3.5.0\conf\setting.xml`中找到`mirrors`:
```xml
alimaven
aliyun maven
http://maven.aliyun.com/nexus/content/groups/public/
central
```


项目结构如下图,手动创建相关文件夹及文件,并设置文件夹的对应属性:


至此,maven工程创建完毕。
## **2. 访问mongodb数据方式**
这里`dao`与`mongoDao`分别为`mongoDB`的两种查询方式:
> (1) `dao`为`JPA`的查询方式(请参考`springdataJPA`);
>
> (2) `mongoDao`使用`mongoTemplate`,类似于关系型数据库使用的`jdbcTemplate`。
## **3. 详细代码**
先看配置文件
spring-context.xml为最基本的`spring`配置:
```xml
```
spring-web.xml为`springmvc`的基本配置:
```xml
```
spring-mongo.xml为mongo配置:
```xml
```
mongo.properties:
```properties
mongo.hostport=10.10.16.234:27017
mongo.connectionsPerHost=8
mongo.threadsAllowedToBlockForConnectionMultiplier=4
#连接超时时间
mongo.connectTimeout=1000
#等待时间
mongo.maxWaitTime=1500
mongo.autoConnectRetry=true
mongo.socketKeepAlive=true
#Socket超时时间
mongo.socketTimeout=1500
mongo.slaveOk=true
```
pom.xml,这里要注意的是`junit`版本需要4.12以上,不然idea会报错;`spring-data-mongodb`版本要1.10.1以上;
```xml
4.0.0
4.3.8.RELEASE
UTF-8
com.liu
mongo
1.0-SNAPSHOT
war
mongo Maven Webapp
http://maven.apache.org
junit
junit
4.12
test
org.slf4j
slf4j-api
1.7.12
ch.qos.logback
logback-core
1.1.1
ch.qos.logback
logback-classic
1.1.1
mysql
mysql-connector-java
5.1.22
runtime
jstl
jstl
1.2
com.fasterxml.jackson.core
jackson-databind
2.5.4
org.springframework
spring-core
4.3.8.RELEASE
org.springframework
spring-asm
3.1.4.RELEASE
org.springframework
spring-beans
4.3.8.RELEASE
org.springframework
spring-context
4.3.8.RELEASE
org.springframework.data
spring-data-mongodb
1.10.1.RELEASE
org.mongodb
mongo-java-driver
3.2.2
org.springframework
spring-tx
${spring.version}
org.springframework
spring-aop
4.3.8.RELEASE
org.springframework
spring-web
4.3.8.RELEASE
org.springframework
spring-webmvc
4.3.8.RELEASE
org.springframework
spring-test
4.3.8.RELEASE
commons-collections
commons-collections
3.2.2
commons-fileupload
commons-fileupload
1.3.2
commons-codec
commons-codec
1.10
javax
javaee-api
7.0
provided
org.springframework
spring-framework-bom
${spring.version}
pom
import
net.sf.ehcache
ehcache-core
2.6.9
mongo
org.apache.maven.plugins
maven-compiler-plugin
3.3
1.6
1.6
```
两个实体类:
Address.java:
```java
package com.lewis.mongo.entity;
/**
* Created by liu on 2017/6/7.
*/
public class Address {
private String city;
private String street;
private int num;
public Address() {
}
public Address(String city, String street, int num) {
this.city = city;
this.street = street;
this.num = num;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
@Override
public String toString() {
return "Address{" +
"city='" + city + '\'' +
", street='" + street + '\'' +
", num=" + num + '}';
}
}
```
Person.java:
```java
package com.lewis.mongo.entity;
import java.io.Serializable;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* Created by liu on 2017/6/7.
*/
@Document(collection = "person")
public class Person implements Serializable {
@Id
private ObjectId id;
private String name;
private int age;
private Address address;
public Person() {
}
public Person(String name, int age, Address address) {
this.name = name;
this.age = age;
this.address = address;
}
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Person{" + "id=" + id +
", name='" + name + '\'' +
", age=" + age +
", address=" + address + '}';
}
}
```
JPA的dao,注意这里只要继承MongoRepository不用写注解spring就能认识这是个Repository,MongoRepository提供了基本的增删改查,不用实现便可直接调用,例如testMongo的personDao.save(persons);
PersonDao.java:
```java
package com.lewis.mongo.dao;
import com.lewis.mongo.entity.Person;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import java.util.List;
/**
* Created by liu on 2017/6/7.
*/
public interface PersonDao extends MongoRepository {
@Query(value = "{'age' : {'$gte' : ?0, '$lte' : ?1}, 'name' : ?2}", fields = "{'name' : 1, 'age' : 1}")
List findByAge(int age1, int age2, String name);
}
```
mongoTemplate的dao,PersonMongoDao.java:
```java
package com.lewis.mongo.mongoDao;
import com.lewis.mongo.entity.Person;
import java.util.List;
/**
* Created by liu on 2017/6/7.
*/
public interface PersonMongoDao {
List findAll();
void insertPerson(Person user);
void removePerson(String userName);
void updatePerson();
List findForRequery(String userName);
}
```
PersonMongoImpl.java:
```java
package com.lewis.mongo.mongoDao;
import com.lewis.mongo.entity.Person;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by liu on 2017/6/7.
*/
@Repository("personMongoImpl")
public class PersonMongoImpl implements PersonMongoDao {
@Resource
private MongoTemplate mongoTemplate;
@Override
public List findAll() {
return mongoTemplate.findAll(Person.class, "person");
}
@Override
public void insertPerson(Person person) {
mongoTemplate.insert(person, "person");
}
@Override
public void removePerson(String userName) {
mongoTemplate.remove(Query.query(Criteria.where("name").is(userName)), "person");
}
@Override
public void updatePerson() {
mongoTemplate.updateMulti(Query.query(Criteria.where("age").gt(3).lte(5)), Update.update("age", 3), "person");
}
@Override
public List findForRequery(String userName) {
return mongoTemplate.find(Query.query(Criteria.where("name").is(userName)), Person.class);
}
}
```
JPA查询的测试类,PersonDaoTest.java:
```java
import com.lewis.mongo.dao.PersonDao;
import com.lewis.mongo.entity.Address;
import com.lewis.mongo.entity.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* Created by liu on 2017/6/7.
*/
@RunWith(SpringJUnit4ClassRunner.class)
//告诉junit spring配置文件
@ContextConfiguration({"classpath:spring/spring-context.xml", "classpath:spring/spring-mongo.xml"})
public class PersonDaoTest {
@Resource
private PersonDao personDao;
/*先往数据库中插入10个person*/
@Test
public void testMongo() {
List persons = new ArrayList();
for (int i = 0; i < 10; i++) {
persons.add(new Person("name" + i, i, new Address("广州市", "天河区", i)));
}
personDao.save(persons);
}
@Test
public void findMongo() {
System.out.println(personDao.findByAge(2, 8, "name6"));
}
}
```
mongoTemplate查询的测试类,MongoTemplateTest.java:
```java
import com.lewis.mongo.entity.Address;
import com.lewis.mongo.entity.Person;
import com.lewis.mongo.mongoDao.PersonMongoImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
/**
* Created by liu on 2017/6/7.
*/
@RunWith(SpringJUnit4ClassRunner.class)
//告诉junit spring配置文件
@ContextConfiguration({"classpath:spring/spring-context.xml", "classpath:spring/spring-mongo.xml"})
public class MongoTemplateTest {
@Resource
private PersonMongoImpl personMongo;
@Test
public void testMongoTemplate() {
//personMongo.insertPerson(new Person("Lewis",24,new Address("广州","天河",20)));
personMongo.removePerson("name3");
personMongo.updatePerson();
System.out.println(personMongo.findAll());
System.out.println(personMongo.findForRequery("Lewis"));
}
}
```
> **注意测试前请先通过`PersonDaoTest.java`中的`testMongo()`方法向数据库中插入数据。**
- **项目源码Git地址,仅供学习使用**:[https://github.com/wonderomg/SpringData-mongdb](https://github.com/wonderomg/SpringData-mongdb)
- 参考资料:http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/
- 参考文章:[http://www.imooc.com/article/13777](http://www.imooc.com/article/13777)