栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【How to Use】Series: How to use MongoDB in SpringBoot?

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【How to Use】Series: How to use MongoDB in SpringBoot?

注意 我们想从mongoDB里面拿东西 不能restAPI controller layer直接请求然后从mongoDB里面拿。而是需要REST API发送请求给service service layer再从DAO里面拿, DAO就是spring Data MongoDB, 然后spring data mongo DB 才可以从DB里面直接拿。

还是少不了这么几个:
在maven的pom.xml中田间dependency: Spring Data MongoDB
在application.preperties中添加config

然后我们需要implement table model. (mongoDB有table一说?)
basically is create the table/entity class, use the annotation @document. ----Not @Entity
如果MongoDB里面有对应的表 那么就对应 没有的话我们就创建一个这样schema的table.

然后我们需要一个DAO层(xxxRepository.java) 负责Object和DB之间的转化 所以我们的API也要搞在这一层 API用于做CRUD 既然CRUD 就涉及到各种query

public interface ItemRepository extends MongoRepository {
    
    @Query("{name:'?0'}")
    GroceryItem findItemByName(String name); //many of the find() related query, is actually uses the **MongoTemplate** to execute
    
    @Query(value="{category:'?0'}", fields="{'name' : 1, 'quantity' : 1}")
    List findAll(String category);
    
    public long count();

}

然后create application class用来运行这个模块(是这个微服务的入口):
会用到一个重要的cnnotation:
@SpringBootApplication: 这个annotation 会自动做下面的:@Configuration @EnableAutoConfig @ComponentScan
main function use SpringApplication.run() to launch the application.

if you want more control over the registration process, you can use the @EnableMongoRepositories.

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/446215.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号