一,MongoDB单机版部署
1.下载安装,已经绑定资源了,linux版和windows版都有,4.0.10版本
2. linux上新建文件夹:
mkdir /usr/local/mongodb
3. 把mongodb-linux-x86_64-4.0.10.tgz上传至上述文件夹,解压
tar -xvf mongodb-linux-x86_64-4.0.10.tgz
修改文件夹名字
mv mongodb-linux-x86_64-4.0.10 mongodb4.0.10
4. 创建db存放的目录和日志存放的目录,新建配置的文件夹并创建配置文件
db存放的目录和日志存放的目录
mkdir /home/mongodb/data/db
mkdir /home/mongodb/log
新建配置的文件夹并创建配置文件
mkdir single
touch mongod.conf
vim mongod.conf
systemLog:
#MongoDB发送所有日志输出的目标指定为文件
# #The path of the log file to which mongod or mongos should send all diagnostic logging information
destination: file
#mongod或mongos应向其发送所有诊断日志记录信息的日志文件的路径
path: "/home/mongodb/log/mongod.log"
#当mongos或mongod实例重新启动时,mongos或mongod会将新条目附加到现有日志文件的末尾。
logAppend: true
storage:
#mongod实例存储其数据的目录。storage.dbPath设置仅适用于mongod。
##The directory where the mongod instance stores its data.Default Value is "/data/db".
dbPath: "/home/mongodb/data/db"
journal:
#启用或禁用持久性日志以确保数据文件保持有效和可恢复。
enabled: true
processManagement:
#启用在后台运行mongos或mongod进程的守护进程模式。
fork: true
net:
#服务实例绑定的IP,默认是localhost,如果是云服务器,这里的ip是内网的(ip a 命令查看),不是外网ip哦
bindIp: localhost,10.0.16.16
#绑定的端口,默认是27017
port: 27017
5. 启动
/usr/local/mongodb/mongodb4.0.10/bin/mongod -f /usr/local/mongodb/single/mongod.conf
用navicat就可以连接了
6. 配置环境变量(想配置的可以配一下)
- 编辑配置文件
vim /etc/profile
- 追加并保存
export PATH=$PATH:/usr/local/mongodb/mongodb4.0.10/bin
- 刷新环境变量
source /etc/profile
7. 数据备份和恢复
- 备份
mongodump --host 127.0.0.1 --port 27017 --db dbname --out /home/mongodb/bak/foldername
- 恢复
mongorestore --host 127.0.0.1 --port 27017 --db dbname /home/mongodb/bak/foldername
二,springboot JPA整合MongoDB,使用MongoTemplate 方式
1. pom配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
完整的
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.wd</groupId>
<artifactId>testMongoDB</artifactId>
<version>1.0-SNAPSHOT</version>
<name>testMongoDB</name>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java/</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
<include>**/*.txt</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2. application.properties配置
spring.data.mongodb.uri=mongodb://localhost:27017/testdb
3. 代码目录:传统的dao service 实体类
4. 写了抽象AbstractMongoMapper类,这个是基类,其他根据业务写就可以了,下面是写了测试例子
import com.mongodb.client.ListIndexesIterable;
import com.mongodb.client.model.Indexes;
import com.mongodb.client.result.DeleteResult;
import org.bson.Document;
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.data.mongodb.core.query.Update;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class AbstractMongoMapper<T> {
@Autowired
private MongoTemplate mongoTemplate;
private Class<T> classT;
public Class<T> getTClass() {
if (classT == null) {
classT = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
return classT;
}
//----------------------------------插入------------------------------------------------
public void insert(T t) {
mongoTemplate.insert(t);
}
public void insertAll(List<T> list) {
mongoTemplate.insertAll(list);
}
public void save(T t) {
mongoTemplate.save(t);
}
//----------------------------------修改------------------------------------------------
public void update(Query query, Update update) {
mongoTemplate.updateFirst(query, update, getTClass());
}
public void updateFirst(Query query, Update update) {
mongoTemplate.updateFirst(query, update, getTClass());
}
public void updateMulti(Query query, Update update) {
mongoTemplate.updateMulti(query, update, getTClass());
}
//----------------------------------删除------------------------------------------------
public long remove(long id) {
Query query = new Query(Criteria.where("id").is(id));
return remove(query);
}
public long remove(Query query) {
DeleteResult remove = mongoTemplate.remove(query, getTClass());
return remove.getDeletedCount();
}
public T removeAndGet(long id) {
Query query = new Query(Criteria.where("id").is(2L));
T t = mongoTemplate.findAndRemove(query, getTClass());
return t;
}
public List<T> removeAndGet(Query query) {
List<T> list = mongoTemplate.findAllAndRemove(query, getTClass());
return list;
}
//----------------------------------查询------------------------------------------------
public List<T> findAll() {
List<T> list = mongoTemplate.findAll(getTClass());
return list;
}
public List<T> findAll(Query query) {
List<T> list = mongoTemplate.find(query, getTClass());
return list;
}
public List<T> findAll(Query query, int limit, int skip) {
if (query == null) {
query = new Query();
}
query.limit(limit).skip(skip);
List<T> list = mongoTemplate.find(query, getTClass());
return list;
}
public long getCount(Query query) {
return mongoTemplate.count(query, getTClass());
}
public Map findPage(Query query, int limit, int skip) {
Map res = new HashMap();
long count = mongoTemplate.count(query, getTClass());
res.put("res", count);
if (count > 0) {
List<T> list = findAll(query, limit, skip);
res.put("data", list);
} else {
res.put("data", new ArrayList<>());
}
return res;
}
//----------------------------------索引------------------------------------------------
/**
* 创建升序索引
*/
public static void createAscendingIndex(MongoTemplate template, String collectionName, String fieldName) {
// 创建索引
template.getCollection(collectionName).createIndex(Indexes.descending(fieldName));
}
/**
* 根据索引名称移除索引
*/
public static void removeIndex(MongoTemplate template, String collectionName, String indexName) {
// 删除索引
template.getCollection(collectionName).dropIndex(indexName);
}
/**
* 查询集合中所有的索引
*/
public static ListIndexesIterable<Document> getIndexAll(MongoTemplate template, String collectionName) {
// 获取集合中所有列表
ListIndexesIterable<Document> indexList = template.getCollection(collectionName).listIndexes();
// 获取集合中全部索引信息
for (Document document : indexList) {
System.out.println("索引列表:" + document);
}
return indexList;
}
}
5. PersonMapper实现dao层的类,主要是用@Component注解,和mysql保持一致的路数
import com.wd.entity.Person;
import org.springframework.stereotype.Component;
@Component
public class PersonMapper extends AbstractMongoMapper<Person> {
}
6. 测试的实体类
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* 指定集合的名称如果不指定
* 默认为当前类名小写
*/
@Document(collection = "person")
public class Person {
@Id
private Long id;
private String name;
private Integer age;
private String parentid;
private Other other;
public Person(Long id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public Person() {
}
/**
* 创建一个10秒自动删除的文档
* 一般结合spring.data.mongodb.auto-index-creation = true 使用
* 注意:这个字段必须是data类型 或者是一个包含data类型的数组字段
*/
// @Indexed(expireAfterSeconds = 30)
// private LocalDateTime createTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getParentid() {
return parentid;
}
public void setParentid(String parentid) {
this.parentid = parentid;
}
public Other getOther() {
return other;
}
public void setOther(Other other) {
this.other = other;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", parentid='" + parentid + '\'' +
", other=" + other +
'}';
}
}
public class Other {
private String l1;
private String l2;
private String l3;
public Other(String l1, String l2, String l3) {
this.l1 = l1;
this.l2 = l2;
this.l3 = l3;
}
public Other() {
}
public String getL1() {
return l1;
}
public void setL1(String l1) {
this.l1 = l1;
}
public String getL2() {
return l2;
}
public void setL2(String l2) {
this.l2 = l2;
}
public String getL3() {
return l3;
}
public void setL3(String l3) {
this.l3 = l3;
}
@Override
public String toString() {
return "Other{" +
"l1='" + l1 + '\'' +
", l2='" + l2 + '\'' +
", l3='" + l3 + '\'' +
'}';
}
}
7. service层
import com.wd.entity.Person;
import com.wd.mapper.PersonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class PersonService {
@Autowired
private PersonMapper personMapper;
public void insert(Person person) {
personMapper.insert(person);
}
public void save(Person person) {
personMapper.save(person);
}
public void update(long id) {
// 查询条件
Query query = Query.query(Criteria.where("_id").is(id));
// 更新条件
Update update = new Update();
update.inc("age");
personMapper.updateFirst(query, update);
}
public List<Person> findAll() {
List<Person> list = personMapper.findAll();
return list;
}
public List<Person> findAll(int limit, int skip) {
Query query = new Query();
query.addCriteria(Criteria.where("age").is(20));
List<Person> list = personMapper.findAll(query, limit, skip);
return list;
}
public long getCount() {
Query query = new Query(Criteria.where("name").regex("^zhang*"));
return personMapper.getCount(query);
}
public Map findPage() {
Query query = new Query(Criteria.where("name").regex("^zhang*"));
return personMapper.findPage(query, 5, 0);
}
public Map findPage(Query query) {
return personMapper.findPage(query, 5, 0);
}
}
8. 测试
System.out.println("-----------------------------------------------------------------------------------------------------");
Person person = new Person(9L, "zhangsan", 20);
person.setParentid("1");
person.setOther(new Other("other1","other2","other3"));
PersonService service = SpringUtil.getBean(PersonService.class);
// service.insert(person);
service.save(person);
service.update(2);
List<Person> commentList = service.findAll();
System.out.println(commentList);
List<Person> all = service.findAll(5, 0);
System.out.println(all);
System.out.println("-------------------------------------------------------");
System.out.println(service.findPage());
System.out.println("--------------------内嵌对象(other)的刷选-----------------------------------");
Query query = new Query(Criteria.where("other.l1").is("other1"));
System.out.println(service.findPage(query));