mongoDB(4) -- Spring Data中使用

  1. 配置數(shù)據(jù)源
spring:
  data:
    mongodb:
      collection: msgDetails
      uri: mongodb://tester01:tester01@127.0.0.1:27016/test
  1. pom 添加依賴包
  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
  1. 注入工具類
@Autowired
    private  MongoTemplate mongoTemplate;
  1. 增刪改查
Test
    public void saveTest() {
        mongoTemplate.save(person);
    }

    @Test
    public void findTest() {
        Person p = mongoTemplate.findOne(query(where("name").is("Joe")), Person.class);
        System.out.println(p);
    }

    @Test
    public void updateTest() {
        mongoTemplate.updateFirst(query(where("name").is("Joe")), update("age", 35), Person.class);
        Person p = mongoTemplate.findOne(query(where("name").is("Joe")), Person.class);
        System.out.println(p);
    }

    @Test
    public void removeTest() {
        List<Person> people =  mongoTemplate.findAll(Person.class);
        System.out.println(people.size());

        Person p = mongoTemplate.findOne(query(where("name").is("Joe")), Person.class);
        mongoTemplate.remove(p);

        people =  mongoTemplate.findAll(Person.class);
        System.out.println(people.size());

        mongoTemplate.dropCollection(Person.class);
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,678評(píng)論 19 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類相關(guān)的語(yǔ)法,內(nèi)部類的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚_t_閱讀 34,806評(píng)論 18 399
  • MongoDB 一、安裝 Windows下,下載安裝包并安裝 在安裝盤的根目錄下,新建data文件夾,里面新建lo...
    Plissmile閱讀 5,562評(píng)論 0 4
  • 1、導(dǎo)入jar包。 org.springframework.boot spring-boot-starter-da...
    彩虹之夢(mèng)閱讀 4,400評(píng)論 0 0
  • 咪咪兩天不吃不喝,只能帶他去就醫(yī)。17年了,這是咪咪第二次走進(jìn)寵物醫(yī)院大門。這家醫(yī)院坐落在南城白紙坊一帶,門臉不大...
    郭子_1788閱讀 894評(píng)論 0 3

友情鏈接更多精彩內(nèi)容