前言
MongoDB是NoSQL的非关系型数据库,他的存储数据可以超过上亿条,mongodb适合存储 一些量大表关系较简单的数据,易于扩展,可以进行分布式文件存储,适用于大数据量、高并发、弱事务的互联网应用,本章主要基于Springboot集成MongoDB实现CRUD相关的功能。
一、搭建Spring工程
Springboot搭建步骤本章就不一一列举,主要描述与mongdb相关的步骤
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--引入mongodb相关的包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!--单元测试依赖包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
## 配置数据库连接
spring.data.mongodb.uri=mongodb://test:123456@192.168.75.31:27017/test
二、定义文档模型
定义模型对象,并使用Mongodb相关的注解进行标识
package com.imk.cases.springboot.mongodb.domain.employee;
import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@Document("Employee")
public class Employee {
private String id;
private String name;
private String email;
private String qq;
public static Employee of(String name , String email){
Employee employee = new Employee();
employee.setName(name);
employee.setEmail(email);
return employee;
}
}
三、继承MongoRepository实现
通过继承MongoRepository实现数据持久化实现
package com.imk.cases.springboot.mongodb.domain.employee;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface IEmployeeRepository extends MongoRepository<Employee,String> {
}
四、MongoRepository实现测试
使用Springboot单元测试功能对mongodb数据持久化CRUD进行测试
package com.imk.cases.springboot.mongodb.domain.employee.impl;
import com.imk.cases.springboot.mongodb.MongodbApplication;
import com.imk.cases.springboot.mongodb.domain.employee.Employee;
import com.imk.cases.springboot.mongodb.domain.employee.IEmployeeRepository;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.*;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import java.util.Optional;
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MongodbApplication.class})
public class EmployeeRepositoryTest {
@Autowired
IEmployeeRepository employeeRepository;
@Test
public void testCreate(){
Employee employee = Employee.of("奔驰E300","12@qq.com");
employeeRepository.insert(employee);
String id = employee.getId();
log.info("testCreate-employee.id={}",id);
Assert.assertNotNull(id);
}
@Test
public void testFindById(){
String id = "6326fbbf7cbcc26c8f8237ac";
Optional<Employee> employee = employeeRepository.findById(id);
log.info("testFindById-employee={}",employee.get());
}
@Test
public void testFindList(){
List<Employee> list = employeeRepository.findAll();
log.info("testFindList-list={}",list);
Assert.assertNotNull(list);
}
@Test
public void testFindPageList(){
Employee employee = Employee.of("奥迪",null);
Page<Employee> page = employeeRepository.findAll(PageRequest.of(0, 2));
List<Employee> content = page.getContent();
log.info("testFindList-list={}",content);
Assert.assertNotNull(content);
}
@Test
public void testUpdate(){
String id = "6326fbbf7cbcc26c8f8237ac";
Employee employee = employeeRepository.findById(id).get();
log.info("testUpdate-employee={}",employee);
employee.setQq("123456");
Employee save = employeeRepository.save(employee);
Assert.assertNotNull(save);
}
}
五、自定义接口通过MongoTemplate实现
通过自定义接口依赖MongoTemplate实现MongoDB数据的持久化
package com.imk.cases.springboot.mongodb.domain.employee;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
public interface IEmployeeRepository2 {
Employee create(Employee employee);
long delete(String id);
long update(Employee employee);
Employee findById(String id);
Page<Employee> findList(Employee employee, Pageable pageable);
}
package com.imk.cases.springboot.mongodb.domain.employee.impl;
import com.imk.cases.springboot.mongodb.domain.employee.Employee;
import com.imk.cases.springboot.mongodb.domain.employee.IEmployeeRepository2;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.bson.Document;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
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.Component;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Objects;
@Component
@RequiredArgsConstructor
public class EmployeeRepository2 implements IEmployeeRepository2 {
private @NonNull MongoTemplate mongoTemplate;
@Override
public Employee create(Employee employee) {
return mongoTemplate.save(employee);
}
@Override
public long delete(String id) {
Query query = new Query(Criteria.where("_id").is(id));
return mongoTemplate.remove(query,Employee.class).getDeletedCount();
}
@Override
public long update(Employee employee) {
Query query = new Query(Criteria.where("_id").is(employee.getId()));
BeanMap beanMap = BeanMap.create(employee);
Update update = Update.fromDocument(new Document( beanMap ), "_class");
return mongoTemplate.updateFirst(query,update,Employee.class).getModifiedCount();
}
@Override
public Employee findById(String id) {
return mongoTemplate.findById(id,Employee.class);
}
@Override
public Page<Employee> findList(Employee employee, Pageable pageable) {
BeanMap beanMap = BeanMap.create(employee);
Document document = new Document();
beanMap.forEach((key,value)->{
if(!Objects.isNull(value) && StringUtils.hasLength(value.toString())){
document.put((String)key,value);
}
});
Query query = new BasicQuery(document);
long count = mongoTemplate.count(query, Employee.class);
query.skip(pageable.getOffset()).limit(pageable.getPageSize());
List<Employee> employeeList = mongoTemplate.find(query, Employee.class);
return new PageImpl<>(employeeList,pageable,count);
}
}
六、自定义接口通过MongoTemplate测试
使用单元测试对自定义接口进行验证
package com.imk.cases.springboot.mongodb.domain.employee.impl;
import com.imk.cases.springboot.mongodb.MongodbApplication;
import com.imk.cases.springboot.mongodb.domain.employee.Employee;
import com.imk.cases.springboot.mongodb.domain.employee.IEmployeeRepository2;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MongodbApplication.class})
public class EmployeeRepository2Test {
@Autowired
IEmployeeRepository2 employeeRepository2;
@Test
public void testCreate(){
Employee employee = Employee.of("奔驰","12@qq.com");
employeeRepository2.create(employee);
String id = employee.getId();
log.info("testCreate-employee.id={}",id);
Assert.assertNotNull(id);
}
@Test
public void testFindById(){
String id = "6326f32ba154c236d6a82e5c";
Employee employee = employeeRepository2.findById(id);
log.info("testFindById-employee={}",employee);
}
@Test
public void testFindPageList(){
Employee employee = Employee.of("",null);
Page<Employee> employeePage = employeeRepository2.findList(employee, PageRequest.of(0,3));
log.info("testFindList-list={}",employeePage.getContent());
Assert.assertNotNull(employeePage.getContent());
}
@Test
public void testUpdate(){
String id = "6326f5bc1537082c23899e25";
Employee employee = employeeRepository2.findById(id);
log.info("testUpdate-employee={}",employee);
employee.setQq("123456");
long update = employeeRepository2.update(employee);
Assert.assertEquals(1L,update);
}
}
七、总结
通过Springboot集成MongoDB实现数据的持久化操作高效且简单,目前有两种方式,分别为:1、使用MongoRepository接口;2、自定义接口+MongoTemplate。于在项目中如何选择可以根据项目业务复杂度进行决策,比如业务比较复杂需要考虑各种扩展就使用第二种方法,反之第一种。
|