SpringBoot整合MongoDB详解
2023-12-14 16:54:47
SpringBoot——整合MongoDB详解
注意: MongoDB默认是本机访问 需要开启远程访问
window修改如下
linux 修改如下
/usr/local/mongodb4/mongodb.conf 详细内容
dbpath=/data/mongodb4/mongo #数据文件保存地址
logpath=/data/mongodb4/log/mongod.log #日志保存地址
port=27017 #端口
fork=true #是否后台启动
auth=true #是否开启权限,访问需要用户名和密码
bind_ip=0.0.0.0 #任意ip都能访问
logappend=true
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
配置文件
spring:
data:
mongodb:
host: 127.0.0.1
database: test
port: 27017
# 也可以使用uri mongodb://127.0.0.1:27017/test
创建实体类
@Data
public class Student {
@Id
private String studentId;
private String studentName;
private Integer studentAge;
private Double studentScore;
private Date studentBirthday;
public Student(String studentId, String studentName, Integer studentAge, Double studentScore, Date studentBirthday) {
this.studentId = studentId;
this.studentName = studentName;
this.studentAge = studentAge;
this.studentScore = studentScore;
this.studentBirthday = studentBirthday;
}
public Student() {
}
}
dao层
1、JPA方式
/**
* JPA方式
* 继承MongoRepository即可,不需要实现类
*/
public interface StudentRepository extends MongoRepository<Student, String> {
}
StudentController
@RestController
public class StudentController {
@Autowired
private StudentRepository studentRepository;
/**
* 插入单条数据
*/
@GetMapping("/insertOne")
public void insertOne() {
Student student = new Student("009", "tom", 18, 88.2d, new Date());
studentRepository.insert(student);
}
/**
* 插入多条数据
*/
@GetMapping("/insertMany")
public void insertMany() {
Student student1 = new Student("002", "jerry", 19, 38.2d, new Date());
Student student2 = new Student("003", "mike", 20, 78.2d, new Date());
List<Student> list = new ArrayList<>();
list.add(student1);
list.add(student2);
studentRepository.insert(list);
}
/**
* 修改数据
*/
@GetMapping("/update")
public void update() {
Optional<Student> op = studentRepository.findById("002");
Student student = op.get();
student.setStudentAge(222);
studentRepository.save(student);
}
/**
* 查询数据
*/
@GetMapping("/query")
public void query() {
//根据Id查询单个对象
Optional<Student> stuOp = studentRepository.findById("002");
System.out.println(stuOp.get());
//根据字段查询单个对象
Student student = new Student();
student.setStudentAge(19);
Optional<Student> stuOp1 = studentRepository.findOne(Example.of(student));
System.out.println(stuOp1.get());
//根据id列表查询多个对象
Iterable<Student> itStu = studentRepository.findAllById(Arrays.asList(new String[]{"002", "003"}));
Iterator<Student> itor = itStu.iterator();
while (itor.hasNext()){
System.out.println(itor.next());
}
//查询所有
List<Student> all = studentRepository.findAll();
//查询所有并排序
List<Student> all1 = studentRepository.findAll(Sort.by(Sort.Order.desc("studentId"), Sort.Order.asc("studentName")));
for (Student stu : all1){
System.out.println(stu);
}
//根据条件查询所有并排序
Student student1 = new Student();
student1.setStudentName("tom");
List<Student> all2 = studentRepository.findAll(Example.of(student1), Sort.by(Sort.Order.desc("studentId"), Sort.Order.asc("studentName")));
for (Student stu : all2){
System.out.println(stu);
}
//根据条件查询所有并排序,且分页
Pageable pageable = PageRequest.of(0, 2);
Page<Student> all3 = studentRepository.findAll(pageable);
List<Student> content = all3.getContent();
for (Student stu : content){
System.out.println(stu);
}
}
/**
* 其他操作
*/
@GetMapping("/other")
public void other() {
//count
long count = studentRepository.count();
System.out.println(count);
Student student = new Student();
student.setStudentAge(18);
long count1 = studentRepository.count(Example.of(student));
System.out.println(count1);
//exists
boolean exists = studentRepository.exists(Example.of(student));
System.out.println(exists);
boolean b = studentRepository.existsById("001");
System.out.println(b);
}
/**
* 删除操作
*/
@GetMapping("/remove")
public void remove() {
//根据id删除单个对象
studentRepository.deleteById("002");
//根据字段删除
Student student = new Student();
student.setStudentAge(20);
studentRepository.delete(student);
//删除所有
studentRepository.deleteAll();
//根据字段删除多个
Student student1 = new Student();
student1.setStudentName("jerry");
List<Student> list = new ArrayList<>();
list.add(student);
list.add(student1);
studentRepository.deleteAll(list);
}
}
2、MongoTemplate方式
dao接口:
public interface StudentDao {
//插入单个对象
void addOne(Student student);
//根据id删除单个对象
void deleteOneById(String studentId);
//修改单个对象
void updateOne(Student student);
//根据id获取单个对象
Student findOneById(String studentId);
//获取全部学生
List<Student> findAll();
}
实现类:
public class StudentDaoImpl implements StudentDao {
@Autowired
private MongoTemplate mongoTemplate;
@Override
public void addOne(Student student) {
mongoTemplate.save(student);
}
@Override
public void deleteOneById(String studentId) {
Student stu = mongoTemplate.findById(studentId, Student.class);
if (stu != null)
mongoTemplate.remove(stu);
}
@Override
public void updateOne(Student student) {
mongoTemplate.save(student);
}
@Override
public Student findOneById(String studentId) {
return mongoTemplate.findById(studentId, Student.class);
}
@Override
public List<Student> findAll() {
return mongoTemplate.findAll(Student.class);
}
}
测试类
@SpringBootTest
public class StudentDaoTest {
@Autowired
private StudentDao studentDao;
@Test
void addOneStudent(){
// 插入10行
for (Integer count = 0; count < 10; count++) {
Student student = new Student();
student.setStudentId("study_"+count);
student.setStudentName("Echo"+count);
student.setStudentAge(count);
student.setStudentScore(98.5-count);
student.setStudentBirthday(new Date());
studentDao.addOne(student);
}
}
@Test
void deleteOneStudentByStudentId(){
// 删除id为study_0的学生
studentDao.deleteOneById("study_0");
}
@Test
void updateOneStudent(){
// 修改id为study_1的Student年龄为21
Student student = studentDao.findOneById("study_1");
student.setStudentAge(21);
studentDao.updateOne(student);
}
@Test
void getOneStudentByStudentId(){
System.out.println(studentDao.findOneById("study_1"));
}
@Test
void getAllStudent(){
List<Student> studentList = studentDao.findAll();
studentList.forEach(System.out::println);
}
}
MongoTemplate
is查询:
Query query = new Query();
// where...is... 相当于 where ? = ?
query.addCriteria(Criteria.where("数据库字段名").is("你的参数"));
// findOne 返回的是一个对象 Class代表你的表对应的映射类
mongoTemplate.findOne(query, Class.class);
// find 返回的是数组
mongoTemplate.find(query, Class.class);
in查询:
ArrayList<String> list = new ArrayList<>();
// list代表你的数据
Query query = Query.query(Criteria.where("数据库字段").in(list));
mongoTemplate.find(query, Class.class);
// 如果想要查询指定的数据是否在数据库的数组中,可以用以下方法
Query query = Query.query(Criteria.where("数据库字段(数组)").is("你的数组"));
字符模糊查询:
Query query = Query.query(Criteria.where("name").regex("小"));
指定字段不返回:
query.fields().exclude("field");
数组中添加或删除一条数据:
Query query = Query.query(Criteria.where("_id").is("id"));
Update update = new Update();
// push方法可以在数组中添加一条数据
// pull方法可以在数组中删除一条数据
// update.pull()
update.push("字段名称", "data");
mongoTemplate.updateFirst(query, update, Class.class);
批量添加:
ArrayList<Class> list = new ArrayList<>();
mongoTemplate.insert(list, Class.class);
数组查询:
数组格式:
{
name:"小明",
age:13,
friends:[
{
name:"小王",
age:12
},
{
name:"小李",
age:18
}
]
}
当要查询朋友中姓名为小王时
Query query = new Query();
query.addCriteria(Criteria.where("friends.$.name").is("小王"));
mongoTemplate.find(query, User.class);
同样更新时也是一样,但是注意,更新时查询条件需要添加
query.addCriteria(Criteria.where("friends").elemMatch(Criteria.where("name").is("小王"));
Update update = Update.update("friends.$.friends", "小赵");
数字字符串排序操作
对数据库中数字字符串排序:
加上这一行就行了 亲身体验
query.collation(Collation.of("zh").numericOrdering(true));
还有根据字符串排序时又是顺序并不是我们所想的字典序,加上下面这个也ok
query.collation(Collation.of("zh"));
分页
//分页
query.limit(10);
//排序
Sort sort=Sort.by(Sort.Direction.DESC,"timestamp");
query.with(sort);
criteria:
2、更新
User user = new User();
user.setId("5d1312aeb1829c279c6c256b");
user.setName("admin");
user.setAddress("测试");
Query query = Query.query(Criteria.where("_id").is("5d1312aeb1829c279c6c256b"));
Update update = Update.update("name","zs");
// 更新一条数据
mongoTemplate.updateFirst(query,update, User.class);
mongoTemplate.updateFirst(query,update, "mongodb_user");
mongoTemplate.updateFirst(query,update, User.class,"mongodb_user");
// 更新多条数据
mongoTemplate.updateMulti(query,update, User.class);
mongoTemplate.updateMulti(query,update,"mongodb_user");
mongoTemplate.updateMulti(query,update, User.class,"mongodb_user");
// 更新数据,如果数据不存在就新增
mongoTemplate.upsert(query,update, User.class);
mongoTemplate.upsert(query,update,"mongodb_user");
mongoTemplate.upsert(query,update, User.class,"mongodb_user");
3、插入
List<User> list = new ArrayList<>();
User user= new User();//
user.setName("admin");
user.setAddress("测试");
list.add(user);
// 保存对象到mongodb
mongoTemplate.save(user);
mongoTemplate.insert(user);
// 根据集合名称保存对象到mongodb
mongoTemplate.save(user,"mongodb_user");
mongoTemplate.insert(user,"mongodb_user");
// 根据集合名称保存list到mongodb
mongoTemplate.save(list,"mongodb_user");
mongoTemplate.insert(list,"mongodb_user");
mongoTemplate.insert(list,User.class);
删除
List<MongoDbJavaTest> list = new ArrayList<>();
User user= new User();
user.setId("5d1312aeb1829c279c6c256b");
list.add(user);
Query query = Query.query(Criteria.where("_id").in("5d1312aeb1829c279c6c256b","5d13133ab1829c29d02ce29c"));
// 根据条件删除
mongoTemplate.remove(query);
mongoTemplate.remove(user);
mongoTemplate.remove(User.class);
// 根据条件删除(可删除多条)
mongoTemplate.remove(query,User.class,"mongodb_user");
文章来源:https://blog.csdn.net/weixin_43564627/article/details/134997152
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!