最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot整合MongoDB的步驟詳解

 更新時間:2021年04月24日 10:00:12   作者:黃河大道東  
這篇文章主要介紹了SpringBoot整合MongoDB的步驟詳解,幫助大家更好的理解和學(xué)習(xí)使用SpringBoot框架,感興趣的朋友可以了解下

項目結(jié)構(gòu):

1.pom引入mongodb依賴

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

2 配置application.properties

#spring.data.mongodb.host=127.0.0.1
#spring.data.mongodb.port=27017
#spring.data.mongodb.database=books
###這種類似于關(guān)系型數(shù)據(jù)庫url配置
spring.data.mongodb.uri=mongodb://127.0.0.1:27017/books

3.創(chuàng)建mongodb文檔映射實體類

@Document(collection = "comment") //如果省略集合屬性,默認(rèn)為類名首字母小寫
//設(shè)置復(fù)合索引
//@CompoundIndex(def="{'userId':1},{'nickName':-1}")
public class Comment implements Serializable {
 
    @Id  //對應(yīng)comment中的_id
    private String id;
    @Field("content")//屬性對應(yīng)mongodb字段名,如果一致,無須該注解
    private String content;//吐槽內(nèi)容
    private String articleId;//文章id
    private Date publishTime;//發(fā)布日期
    @Indexed  //添加一個單字段的索引
    private String userId;//發(fā)布人id
    private String nickName;//發(fā)布人昵稱
    private Date createDateTime;//評論的日期時間
    private Integer likeNum;//點贊數(shù)
    private Integer replyNum;//回復(fù)數(shù)
    private String state;//狀態(tài)
    private String parentId;//上級id
	// 此處忽略getter與setter方法
} 

SpringBoot中MongoDB常用注解:

  1. @Document

標(biāo)注在實體類上,將java類聲明為mongodb的文檔,可以通過collection參數(shù)指定這個類對應(yīng)的文檔。類似于Hibernate的entity注解,表明由mongo來維護該集合(表)。

  1. @id

主鍵,不可重復(fù),自帶索引,可以在定義的列名上標(biāo)注,需要自己生成并維護不重復(fù)的約束。
如果自己不設(shè)置@Id主鍵,mongo會自動生成一個唯一主鍵,插入效率遠(yuǎn)高于自己設(shè)置主鍵。
在實際業(yè)務(wù)中不建議自己設(shè)置主鍵,應(yīng)交給mongo自己生成,可以另外設(shè)置一個業(yè)務(wù)id,如int型字段,用自己設(shè)置的業(yè)務(wù)id來維護相關(guān)聯(lián)的集合(表)。

  1. @Indexed

聲明該字段需要加索引,加索引后以該字段為條件檢索將大大提高速度。
唯一索引的話是@Indexed(unique = true)。
也可以對數(shù)組進行索引,如果被索引的列是數(shù)組時,MongoDB會索引這個數(shù)組中的每一個元素。
也可以對整個Document進行索引,排序是預(yù)定義的按插入BSON數(shù)據(jù)的先后升序排列。

  1. @CompoundIndex

復(fù)合索引,加復(fù)合索引后通過復(fù)合索引字段查詢將大大提高速度。

  1. @Field

實體類屬性對應(yīng)集合(表)字段名,如果一致,無須該注解

4.service業(yè)務(wù)層

CommonService,操作mongo的具體業(yè)務(wù)類

采用Repository和MongoTemplate兩種方式來實現(xiàn)的;Repository 提供最基本的數(shù)據(jù)訪問功能,其幾個子接口則擴展了一些功能。

MongoTemplate核心操作類:Criteria和Query

  • Criteria類:封裝所有的語句,以方法的形式查詢。
  • Query類:將語句進行封裝或者添加排序之類的操作。
@Service
public class CommentService {
 
    @Autowired
    private CommentRepository commentRepository;  // 注入DAO
 
    @Autowired
    private MongoTemplate mongoTemplate;  // 注入Mongodb提供的操作模板
 
	// 保存一個
    public void saveComment(Comment comment){
        commentRepository.save(comment);
       // mongoTemplate.save(comment);
       // mongoTemplate.insert(comment);
    }
 
	// 批量保存
    public void mutilSaveComment(List<Comment> list){
        commentRepository.saveAll(list);
       // mongoTemplate.insertAll(list);
    }
 
    // 更新一個
    public void updateComment(Comment comment){
         commentRepository.save(comment);
    }
 
   	// 查詢?nèi)?
    public List<Comment> findCommentAll(){
       // return  commentRepository.findAll();
        return mongoTemplate.findAll(Comment.class);
    }
 
    // 條件查詢
    public List<Comment> findCommentByContion(Query query){
        return  mongoTemplate.find(query,Comment.class);
    }
 
    // 查詢?nèi)坎⒁詉d排序返回結(jié)果
    public List<Comment> findCommentAllOrder(){
      //  return  commentRepository.findAll(Sort.by(Sort.Order.desc("_id")));
 
		Query query=new Query();
		query.with(Sort.by(Sort.Direction.DESC,"id"));
		return mongoTemplate.find(query,Comment.class);
    }
 
 
    // 通過id查詢
    public Comment findCommentById(String id){
        //return  commentRepository.findById(id).get();
        return mongoTemplate.findById(id,Comment.class);
    }
 
    /**
     * @param parentId
     * @param page
     * @param size
     * @return
     */
    public Page<Comment> findByparentIdPage1(String parentId, int page,int size){
        return  commentRepository.findByParentId(parentId, PageRequest.of(page-1,size));
    }
 	
    // 方式二
    public List<Comment> findByparentIdPage2(String parentId, int page,int size){
        Query query=Query.query(Criteria.where("parentId").is(parentId));
        query.with(PageRequest.of(page-1,size));
        return  mongoTemplate.find(query,Comment.class);
    }
 
    // 通過id刪除
    public void deleteById(String id){
        // commentRepository.deleteById(id);
        Comment comment=new Comment();
        comment.setId(id);
        mongoTemplate.remove(comment);
    }
 

    // 刪除全部數(shù)據(jù)
    public void deleteAll(){
        commentRepository.deleteAll();
    }
 
    // 批量刪除
    public void deleteMulti(List<Comment> list){
        commentRepository.deleteAll(list);
    }
 

	// 根據(jù)id更新一條文檔:點贊數(shù)加1
    public void updateCommentLikeNumm(String id){
		// 點贊數(shù)加一,效率低,增加id開銷
		// Comment comment=commentRepository.findById(id).get();
		// comment.setLikeNum(comment.getLikeNum()+1);
		// commentRepository.save(comment);
 
		// 拿到查詢對象
        Query query=Query.query(Criteria.where("_id").is(id));
        // 拿到更新對象
        Update update=new Update();
		// 局部更新 相當(dāng)于$set
		// update.set(key,value);
		// 遞增$inc
        // update.inc("likeNum",1);
        update.inc("likeNum");  // 指定字段自增1
        mongoTemplate.updateFirst(query,update,"comment");
    }
 
    // 有條件的統(tǒng)計
    public Long commentCount(Query query){
        return mongoTemplate.count(query,Comment.class);
    }
}

5.DAO層

dao層CommentRepository 繼承MongoRepository,MongoRepository中已經(jīng)預(yù)定義了一些增刪查的方法,根據(jù)JPA的命名規(guī)范可以定義一些查詢方法,不需要具體實現(xiàn),底層會幫你實現(xiàn)。

public interface CommentRepository extends MongoRepository<Comment,String> {
  //新增按父id分頁查詢
    Page<Comment> findByParentId(String parentId,Pageable pageable);
}  

6.測試

@RunWith(SpringRunner.class)
@SpringBootTest
public class CommentServiceTest {
 
    @Autowired
    private CommentService commentService;
 
    @Test
    public void saveCommentTest(){  // 新增單個
        Comment comment=new Comment();
        //comment.setId("2");
        comment.setArticleId("777");
        comment.setContent("添加數(shù)據(jù)測試");
        comment.setPublishTime(new Date());
        comment.setUserId("1001");
        comment.setNickName("張三");
        comment.setCreateDateTime(new Date());
        comment.setLikeNum(1);
        comment.setReplyNum(0);
        comment.setState("1");
        comment.setParentId("0");
        commentService.saveComment(comment);
    }
 
    @Test
    public void mutilSaveComment(){  // 批量新增
        List<Comment> list=new ArrayList<>();
        Comment comment;
        for(int i=1;i<=10;i++){
            comment=new Comment();
            comment.setId(""+i);
            comment.setArticleId(""+i);
            comment.setContent("添加數(shù)據(jù)測試"+i);
            comment.setPublishTime(new Date());
            comment.setUserId("1001");
            comment.setNickName("張三");
            comment.setCreateDateTime(new Date());
            comment.setLikeNum(0);
            comment.setReplyNum(0);
            comment.setState("1");
            comment.setParentId("0");
            list.add(comment);
        }
        commentService.mutilSaveComment(list);
    }
 
    @Test
    public void findCommentListTest() {  // 查詢?nèi)?
        List<Comment> list=commentService.findCommentAll();
        for(Comment comment:list){
            System.out.println(comment);
        }
    }
 
    @Test
    public void findCommentListOrderTest() {  // 查全部并通對id排序
        List<Comment> list=commentService.findCommentAllOrder();
        for(Comment comment:list){
            System.out.println(comment);
        }
    }
 

    @Test
    public void findCommentById() {  // 通過id刪除
        Comment comment=commentService.findCommentById("1");
        System.out.println(comment);
    }
 

    @Test
    public void findByParentId(){  // 通過父id分頁查詢1
        Page<Comment> page=commentService.findByparentIdPage1("0",1,10);  // 第1頁,每頁10個
        System.out.println(page.getTotalElements());
        System.out.println(page.getContent());
    }
 

    @Test
    public void findByparentIdPage2(){  //  通過父id分頁查詢2
        List<Comment> list=commentService.findByparentIdPage2("0",1,10);  // 第1頁,每頁10個
        for(Comment comment1:list){
            System.out.println(comment1);
        }
    }
 
    @Test
    public void deleteById(){  // 通過id刪除評論
        commentService.deleteById("1");
    }
 

    @Test
    public void deleteAll(){  // 刪除全部
        commentService.deleteAll();
    }
 
    @Test
    public void deleteMulti(){  // 批量刪除
        List<Comment> list=new ArrayList<>();
        Comment comment;
        for(int i=1;i<=10;i++) {
            comment = new Comment();
            comment.setId("" + i);
            list.add(comment);
        }
        commentService.deleteMulti(list);
    }
 
    @Test
    public void findCommentByContion(){ // 多條件查詢in
       	// 拿到查詢范圍
        List<String> list=new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        
        // 根據(jù)范圍拿到查詢對象
        Query query=Query.query(Criteria.where("_id").in(list));
 		
        // 根據(jù)查詢條件拿到結(jié)果
        List<Comment> list2=commentService.findCommentByContion(query);
        for(Comment comment1:list2){
            System.out.println(comment1);
        }
    }
 
    @Test
    public void findCommentContionByGtLt(){  // 多條件查詢大于2小于等于6
        // 拿到查詢對象
        Query query=Query.query(Criteria.where("likeNum").gte(2).lte(6));
        // 根據(jù)查詢條件拿到結(jié)果
        List<Comment> list =commentService.findCommentByContion(query);
        for(Comment comment1:list){
            System.out.println(comment1);
        }
    }
 
    @Test
    public void findCommentContionByAnd(){  // 多條件查詢and
        //查詢對象
        Query query=Query.query(new Criteria().andOperator(Criteria.where("likeNum").gte(2)
                                             ,Criteria.where("state").is("1")));
        List<Comment> list =commentService.findCommentByContion(query);
        for(Comment comment1:list){
            System.out.println(comment1);
        }
    }
 
    @Test
    public void findCommentContionByOr(){ // 多條件查詢or
        //查詢對象
        Query query=Query.query(new Criteria().orOperator(Criteria.where("likeNum").gte(2)
                                            ,Criteria.where("state").is("0")));
        List<Comment> list =commentService.findCommentByContion(query);
        for(Comment comment1:list){
            System.out.println(comment1);
        }
    }
 
    @Test
    public void updateCommentLikeNumm(){  // 更新 點贊數(shù)加一
        commentService.updateCommentLikeNumm("1");
    }
 
    @Test
    public void commentCount(){  // 統(tǒng)計查詢
        Query query=Query.query(Criteria.where("likeNum").gte(2));  // 拿到查詢器
        Query query1=new Query();  
        Long count1=commentService.commentCount(query);  // 查符合條件的文檔個數(shù)
        Long count2=commentService.commentCount(query1);  // 查全部
        System.out.println("點贊數(shù)大于等于2的文檔有======="+count1);
        System.out.println("統(tǒng)計總數(shù)======="+count2);
    }
}

到此已經(jīng)在SpringBoot項目中引入了MongoDB,并通過MongoRepository和MongoTemplate兩種方式來實現(xiàn)了基本的增刪改查操。

以上就是SpringBoot整合MongoDB的步驟詳解的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot整合MongoDB的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • java實現(xiàn)文件拷貝的七種方式

    java實現(xiàn)文件拷貝的七種方式

    這篇文章主要介紹了java實現(xiàn)文件拷貝的七種方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-02-02
  • 使用Spring由構(gòu)造方法自動裝配

    使用Spring由構(gòu)造方法自動裝配

    這篇文章主要介紹了使用Spring由構(gòu)造方法自動裝配,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • Java中的static和final關(guān)鍵字的使用詳解

    Java中的static和final關(guān)鍵字的使用詳解

    這篇文章主要介紹了Java中的static和final關(guān)鍵字的使用詳解,  當(dāng)方法名前有static,即為static方法,可以方便我們無需創(chuàng)建對象也可以調(diào)用此方法,靜態(tài)方法比較拉,只可以訪問 靜態(tài)的 屬性/變量/方法,無法訪問非靜態(tài)的這些屬性/變量/方法,需要的朋友可以參考下
    2024-01-01
  • SpringMVC加載控制與Postmand的使用和Rest風(fēng)格的引入及RestFul開發(fā)全面詳解

    SpringMVC加載控制與Postmand的使用和Rest風(fēng)格的引入及RestFul開發(fā)全面詳解

    SpringMVC是一種基于Java,實現(xiàn)了Web MVC設(shè)計模式,請求驅(qū)動類型的輕量級Web框架,即使用了MVC架構(gòu)模式的思想,將Web層進行職責(zé)解耦?;谡埱篁?qū)動指的就是使用請求-響應(yīng)模型,框架的目的就是幫助我們簡化開發(fā),SpringMVC也是要簡化我們?nèi)粘eb開發(fā)
    2022-10-10
  • Java向數(shù)據(jù)庫插入中文出現(xiàn)亂碼解決方案

    Java向數(shù)據(jù)庫插入中文出現(xiàn)亂碼解決方案

    這篇文章主要介紹了Java向數(shù)據(jù)庫插入中文出現(xiàn)亂碼解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-08-08
  • Eclipse配置使用web.xml的方法

    Eclipse配置使用web.xml的方法

    這篇文章主要為大家詳細(xì)介紹了Eclipse配置使用web.xml的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-03-03
  • 基于dubbo分組group的一些總結(jié)

    基于dubbo分組group的一些總結(jié)

    這篇文章主要介紹了關(guān)于dubbo分組group的一些總結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • Java線程代碼的實現(xiàn)方法

    Java線程代碼的實現(xiàn)方法

    下面小編就為大家?guī)硪黄狫ava線程代碼的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-08-08
  • 淺析Spring基于注解的AOP

    淺析Spring基于注解的AOP

    Spring是一個廣泛應(yīng)用的框架,SpringAOP則是Spring提供的一個標(biāo)準(zhǔn)易用的aop框架,依托Spring的IOC容器,提供了極強的AOP擴展增強能力,對項目開發(fā)提供了極大地便利
    2022-11-11
  • springboot websocket集群(stomp協(xié)議)連接時候傳遞參數(shù)

    springboot websocket集群(stomp協(xié)議)連接時候傳遞參數(shù)

    這篇文章主要介紹了springboot websocket集群(stomp協(xié)議)連接時候傳遞參數(shù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07

最新評論

繁峙县| 喀喇沁旗| 得荣县| 旌德县| 马公市| 应城市| 泸水县| 沙田区| 宜兰市| 福安市| 沙田区| 博乐市| 康定县| 灌南县| 盐边县| 东山县| 罗甸县| 瓦房店市| 华宁县| 潜山县| 崇左市| 鲜城| 吉安县| 中方县| 隆林| 专栏| 股票| 莱西市| 南康市| 固始县| 兴山县| 凤冈县| 凤凰县| 保康县| 英吉沙县| 泗洪县| 武夷山市| 和林格尔县| 沾化县| 襄城县| 彭泽县|