MongoDB之整合SpringBoot

MongoTemplate 方式

依赖

xml 复制代码
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
  </dependency>

创建账户

shell 复制代码
# 切换到数据库
use study
# 创建账户
db.createUser({user:"root",pwd:"123456",roles:[{role:"dbOwner",db:"study"}]})

配置文件

properties 复制代码
spring.data.mongodb.host=192.168.204.156
spring.data.mongodb.port=27017
spring.data.mongodb.database=study
spring.data.mongodb.password=123456
spring.data.mongodb.username=root

测试

java 复制代码
@SpringBootTest(classes = {SpringbootMongodbDemoApplication.class})
public class Main {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Test
    public void testAddData() {
        // 添加
        Goods goods = Goods.builder().qty(100).item("hello").status("B").size(new Size(165.0F, 53.4F, "cm")).build();
        mongoTemplate.save(goods, "goods");
        // 查询
        List<Goods> list = mongoTemplate.findAll(Goods.class);
        list.forEach(item -> System.out.println(item.toString()));
    }


}



@Data
@Builder
public class Goods {

    private String id;
    private String item;
    private Integer qty;

    private Size size;

    private String status;

}


@Data
@NoArgsConstructor
@AllArgsConstructor
public class Size {
    private Float h;
    private Float w;
    private String uom;

}

增删改查

java 复制代码
import com.example.springbootmongodbdemo.SpringbootMongodbDemoApplication;
import com.example.springbootmongodbdemo.model.Goods;
import com.example.springbootmongodbdemo.model.Size;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

import static org.springframework.data.mongodb.core.query.Criteria.where;

@SpringBootTest(classes = {SpringbootMongodbDemoApplication.class})
public class Main {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Test
    public void addData() {
        Goods build = Goods.builder().qty(100).item("hello").status("B").size(new Size(165.0F, 53.4F, "cm")).build();
        mongoTemplate.save(build, "goods");
    }

    @Test
    public void findAll() {
        List<Goods> all = mongoTemplate.findAll(Goods.class);
        all.forEach(item -> System.out.println(item.toString()));
    }

    @Test
    public void findById() {
        Goods build = Goods.builder().id("63bbdac2fa9405a15160f476").build();
        Query query = new Query(where("id").is(build.getId()));
        List<Goods> goods = mongoTemplate.find(query, Goods.class);
        System.out.println(goods.toString());
    }

    @Test
    public void findBy() {
        // 匹配r结尾的数据
        Query query = new Query(where("item").regex("^.*r$"));
        List<Goods> goods = mongoTemplate.find(query, Goods.class);
        System.out.println(goods.toString());
    }

    @Test
    public void update() {
        Goods build = Goods.builder().id("63bbdac2fa9405a15160f476").build();
        Query query = new Query(where("id").is(build.getId()));
        Update update = Update.update("item", "canvas02");
        UpdateResult updateResult = mongoTemplate.updateMulti(query, update, Goods.class);
        System.out.println(updateResult);
    }

    @Test
    public void del() {
        Goods build = Goods.builder().id("63d0eff1d20d7f153665244d").build();
        Query query = new Query(where("id").is(build.getId()));
        DeleteResult remove = mongoTemplate.remove(query, Goods.class);
        System.out.println(remove);
    }
}

MongoRepository 方式

依赖&配置

同上。

实体类

java 复制代码
// 关键注解:@Document,@Id
@Data
@Builder
@Document("goods")
public class Goods {

    @Id
    private String id;
    private String item;
    private Integer qty;

    private Size size;

    private String status;

}

接口类

java 复制代码
public interface GoodsRepository extends MongoRepository<Goods, String> {
}

测试

java 复制代码
@SpringBootTest(classes = {SpringbootMongodbDemoApplication.class})
public class Main {

    @Resource
    private GoodsRepository goodsRepository;

    @Test
    public void testAddData() {
        Goods build = Goods.builder().qty(100).item("hello").status("B").size(new Size(165.0F, 53.4F, "cm")).build();
        Goods save = goodsRepository.save(build);
        System.out.println(save);
    }
}
相关推荐
Future_yzx1 小时前
基于SpringBoot+WebSocket的前后端连接,并接入文心一言大模型API
spring boot·websocket·文心一言
落霞的思绪5 小时前
Redis实战(黑马点评)——关于缓存(缓存更新策略、缓存穿透、缓存雪崩、缓存击穿、Redis工具)
数据库·spring boot·redis·后端·缓存
java冯坚持5 小时前
shiro学习五:使用springboot整合shiro。在前面学习四的基础上,增加shiro的缓存机制,源码讲解:认证缓存、授权缓存。
spring boot·学习·缓存
customer0812 小时前
【开源免费】基于SpringBoot+Vue.JS校园失物招领系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源
中國移动丶移不动13 小时前
Java 反射与动态代理:实践中的应用与陷阱
java·spring boot·后端·spring·mybatis·hibernate
老大白菜13 小时前
GoFrame MongoDB 使用指南
数据库·mongodb
杰九16 小时前
【全栈】SprintBoot+vue3迷你商城(9)
前端·javascript·vue.js·spring boot
axinawang17 小时前
Spring Boot是什么及其优点
java·spring boot·后端
神马都会亿点点的毛毛张17 小时前
【SpringBoot教程】Spring Boot + MySQL + HikariCP 连接池整合教程
spring boot·后端·mysql·hikaricp·数据库连接池
yuanpan18 小时前
MongoDB的读写分离技术方案
数据库·mongodb