上节说道mongodb的特性以及组成部分,这节介绍springboot如何快速的整合mongodb,完成我们的需求。
一.依赖
创建SpringBoot工程,添加吐下依赖 可在创建工程时nosql那栏选择。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
二、配置文件
spring:
data:
mongodb:
uri: mongodb://172.16.32.16:27017/data_record?maxPoolSize=500
option:
min-connection-per-host: 0
max-connection-per-host: 100
threads-allowed-to-block-for-connection-multiplier: 5
server-selection-timeout: 30000
max-wait-time: 120000
max-connection-idle-time: 0
max-connection-life-time: 0
connect-timeout: 10000
socket-timeout: 0
socket-keep-alive: false
ssl-enabled: false
ssl-invalid-host-name-allowed: false
always-use-m-beans: false
heartbeat-socket-timeout: 20000
heartbeat-connect-timeout: 20000
min-heartbeat-frequency: 500
heartbeat-frequency: 10000
local-threshold: 15
mongodb数据库与mysql不一样 mysql 一个普通用户可以管理多个数据库,但是mongo每一个库都有一个独立的管理用户,连接时需要输入对应用户密码
三、创建实体类
package com.kn.pojo;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.time.LocalDateTime;
@Data
@Document(collection = "topic_test") //指定要对应的文档名(表名)
public class Student {
/*** 自定义mongo主键 加此注解可自定义主键类型以及自定义自增规则
* 若不加 插入数据数会默认生成 ObjectId 类型的_id 字段
* org.springframework.data.annotation.Id 包下
* mongo库主键字段还是为_id (本文实体类中字段为为id,意思查询字段为_id,但查询结果_id会映射到实体对象id字段中)
*/
@Id
private Integer id;
private String username;
private int age;
private LocalDateTime timer;
}
四、编写方法
1、controller方法
package com.kn.controller;
import com.kn.pojo.Student;
import com.kn.repository.CommentRepository;
import com.kn.service.TopicTestService;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("mongodb")
public class TopicTestController {
@Autowired
TopicTestService topicTestService;
@Autowired
CommentRepository commentRepository;
@Autowired
MongoTemplate mongoTemplate;
/**
* 新增数据
* @param student
* @return
*/
@PostMapping("/insert")
public int insertStudent(@RequestBody Student student){
List<Student> list =new ArrayList<>();
for (int i = 10; i <20; i++) {
Student student1=new Student();
student1.setId(i);
student1.setUsername("张三"+i);
student1.setTimer(LocalDateTime.now());
list.add(student1);
}
//单条插入
return topicTestService.insertStudent(student);
//批量插入
// List<Student> list1 = commentRepository.saveAll(list);
// System.out.println(list1);
// return 1;
}
/**
* 修改数据
* @param student
* @return
*/
@PostMapping("/update")
public int updateStudent(@RequestBody Student student){
return topicTestService.updateStudent(student);
// commentRepository.save(student);
// return 1;
}
/**
* 删除数据
* @param
* @return
*/
@GetMapping("/delete")
public int deleteStudent(@RequestParam Integer id){
return topicTestService.deleteStudent(id);
}
/**
* 查询数据
* @param
* @return
*/
@PostMapping("/select")
public Student selectStudent(@RequestBody Student id){
return topicTestService.selectStudent(id);
}
/**
* 模糊查询数据
* @param
* @return
*/
@PostMapping("/vague")
public List<Student> vagueStudent(@RequestBody Student id){
return topicTestService.vagueStudent(id);
}
/**
* 分页查询数据
* @param
* @return
*/
@PostMapping("/paging")
public List<Student> pagingStudent(@RequestBody Student id){
int pageIndex=1;
int pageSize =3;
Query query = new Query();
Pageable pageable = PageRequest.of(pageIndex, pageSize);
query.with(pageable);
// query.with(Sort.by(Sort.Order.desc(orderBy)));
return mongoTemplate.find(query, Student.class);
}
}
2、service方法
package com.kn.service.impl;
import com.kn.pojo.Student;
import com.kn.service.TopicTestService;
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 org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.regex.Pattern;
@Service
public class TopicTestServiceimpl implements TopicTestService {
@Autowired
MongoTemplate mongoTemplate;
@Override
public int insertStudent(Student student) {
student.setTimer(LocalDateTime.now());
mongoTemplate.insert(student);
return 1;
}
@Override
public int updateStudent(Student student) {
//通过query根据id查询出对应对象,通过update对象进行修改
Query query = new Query(Criteria.where("_id").is(student.getId()));
Update update = new Update().set("username", student.getUsername());
mongoTemplate.updateFirst(query, update, Student.class);
return 1;
}
@Override
public int deleteStudent(Integer id) {
Query query = new Query(Criteria.where("_id").is(id));
mongoTemplate.remove(query, Student.class);
return 1;
}
@Override
public Student selectStudent(Student student) {
Query query = new Query(Criteria.where("username").is(student.getUsername()));
return mongoTemplate.findOne(query, Student.class);
}
@Override
public List<Student> vagueStudent(Student student) {
Pattern pattern = Pattern.compile("^.*" + student.getUsername().trim() + ".*$", Pattern.CASE_INSENSITIVE);
Query query = new Query(Criteria.where("username").regex(pattern));
return mongoTemplate.find(query, Student.class);
}
}
也可以使用Repository实现
通过实现MongoRepository<T, ID>
接口,创建Repository
类,其中T
表示实体类的class,ID
表示主键的数据类型,比如:
public interface CommentRepository extends MongoRepository<Comment, String> {}
稍后补充