mongodb和spring集成中MongoTemplate的总结是使用方法

2023-10-19 10:38

本文主要是介绍mongodb和spring集成中MongoTemplate的总结是使用方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 文档下载地址: http://download.csdn.net/detail/ruishenh/6591721

 

 

  1. 基础实体类

@Document(collection="person")

class Person{

   

    String id;

   

    String name;

   

    int age;

   

    public String getId() {

       returnid;

    }

    public void setId(String id) {

       this.id = id;

    }

    public String getName() {

       returnname;

    }

    public void setName(String name) {

       this.name = name;

    }

    public int getAge() {

       returnage;

    }

    public void setAge(int age) {

       this.age = age;

    }

}

 

 

 

 

 

 

 

         /**

          * The collection name used for the specifiedclass by this template.

          *

          * @param entityClass must not be {@literalnull}.

          * @return

          */

       StringgetCollectionName(Class<?> entityClass);

String personName=mongoTemplate.getCollectionName(Person.class);

 

 

 

         /**

          * Execute the a MongoDB command expressed as aJSON string. This will call the method JSON.parse that is part of the

          * MongoDB driver to convert the JSON string toa DBObject. Any errors that result from executing this command will be

          * converted into Spring's DAO exceptionhierarchy.

          *

          * @param jsonCommand a MongoDB commandexpressed as a JSON string.

          */

       CommandResultexecuteCommand(String jsonCommand);

 

    String jsonSql="{distinct:'person', key:'name'}";

       CommandResult  commandResult=mongoTemplate.executeCommand(jsonSql);

       System.out.println();

        BasicDBList list = (BasicDBList)commandResult.get("values"); 

            for (int i = 0; i < list.size(); i ++) { 

                System.out.println(list.get(i)); 

            } 

       System.out.println();

 

 

         /**

          * Execute a MongoDB command. Any errors thatresult from executing this command will be converted into Spring's DAO

          * exception hierarchy.

          *

          * @param command a MongoDB command

          */

       CommandResultexecuteCommand(DBObject command);

    String jsonSql="{distinct:'person', key:'name'}";

       CommandResult  commandResult=mongoTemplate.executeCommand((DBObject) JSON.parse(jsonSql));

       System.out.println();

        BasicDBList list = (BasicDBList)commandResult.get("values"); 

            for (int i = 0; i < list.size(); i ++) { 

                System.out.println(list.get(i)); 

            } 

       System.out.println();

 

 

 

         /**

          * Execute a MongoDB command. Any errors thatresult from executing this command will be converted into Spring's DAO

          * exception hierarchy.

          *

          * @param command a MongoDB command

          * @param options query options to use

          */

       CommandResultexecuteCommand(DBObject command, int options);

    String jsonSql="{distinct:'person', key:'name'}";

       CommandResult  commandResult=mongoTemplate.executeCommand((DBObject) JSON.parse(jsonSql),Bytes.QUERYOPTION_NOTIMEOUT);

       System.out.println();

        BasicDBList list = (BasicDBList)commandResult.get("values"); 

            for (int i = 0; i < list.size(); i ++) { 

                System.out.println(list.get(i)); 

            } 

       System.out.println();

 

         /**

          * Execute a MongoDB query and iterate over thequery results on a per-document basis with a DocumentCallbackHandler.

          *

          * @param query the query class that specifiesthe criteria used to find a record and also an optional fields

          *         specification

          * @param collectionName name of the collectionto retrieve the objects from

          * @param dch the handler that will extractresults, one document at a time

          */

       void executeQuery(Queryquery, String collectionName, DocumentCallbackHandler dch);

final Query query =new Query();

       Criteria criteria =new Criteria();

       criteria.and("name").is("zhangsan");

       mongoTemplate.executeQuery(query,"person",new DocumentCallbackHandler() {

           //处理自己的逻辑,这种为了有特殊需要功能的留的开放接口命令模式

           public void processDocument(DBObject dbObject) throws MongoException,

                  DataAccessException {

              mongoTemplate.updateFirst(query, Update.update("name","houchangren"),"person");

           }

        });

 

         /**

          * Executes a {@link DbCallback} translatingany exceptions as necessary.

          * <p/>

          * Allows for returning a result object, thatis a domain object or a collection of domain objects.

          *

          * @param <T> return type

          * @param action callback object that specifiesthe MongoDB actions to perform on the passed in DB instance.

          * @return a result object returned by theaction or <tt>null</tt>

          */

       <T> Texecute(DbCallback<T> action);

Person person=mongoTemplate.execute(new DbCallback<Person>() {

           public Person doInDB(DB db)throws MongoException, DataAccessException {

              Person p=new Person();

              //自己写逻辑和查询处理

//            p.setAge(age);

              return p;

           }

       });

 

         /**

          * Executes the given {@linkCollectionCallback} on the entity collection of the specified class.

          * <p/>

          * Allows for returning a result object, thatis a domain object or a collection of domain objects.

          *

          * @param entityClass class that determines thecollection to use

          * @param <T> return type

          * @param action callback object that specifiesthe MongoDB action

          * @return a result object returned by theaction or <tt>null</tt>

          */

       <T> Texecute(Class<?> entityClass, CollectionCallback<T> action);

Person person=mongoTemplate.execute(Person.class,new CollectionCallback<Person>() {

 

           public Person doInCollection(DBCollection collection)

                  throws MongoException, DataAccessException {

              Person p=new Person();

              //自己取值然后处理返回对应的处理  collection.find();

              return  p;

           }

       });

 

 

         /**

          * Executes the given {@linkCollectionCallback} on the collection of the given name.

          * <p/>

          * Allows for returning a result object, thatis a domain object or a collection of domain objects.

          *

          * @param <T> return type

          * @param collectionName the name of thecollection that specifies which DBCollection instance will be passed into

          * @param action callback object that specifiesthe MongoDB action the callback action.

          * @return a result object returned by theaction or <tt>null</tt>

          */

       <T> Texecute(String collectionName, CollectionCallback<T> action);

Person person=mongoTemplate.execute(“person”,new CollectionCallback<Person>() {

 

           public Person doInCollection(DBCollection collection)

                  throws MongoException, DataAccessException {

               Person p=new Person();

              //自己取值然后处理返回对应的处理  collection.find();

              return  p;

           }

       });

 

         /**

          * Executes the given {@link DbCallback} withinthe same connection to the database so as to ensure consistency in a

          * write heavy environment where you may readthe data that you wrote. See the comments on {@see <a

          *href=http://www.mongodb.org/displ

这篇关于mongodb和spring集成中MongoTemplate的总结是使用方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/239232

相关文章

Java 正则表达式URL 匹配与源码全解析

《Java正则表达式URL匹配与源码全解析》在Web应用开发中,我们经常需要对URL进行格式验证,今天我们结合Java的Pattern和Matcher类,深入理解正则表达式在实际应用中... 目录1.正则表达式分解:2. 添加域名匹配 (2)3. 添加路径和查询参数匹配 (3) 4. 最终优化版本5.设计思

Java使用ANTLR4对Lua脚本语法校验详解

《Java使用ANTLR4对Lua脚本语法校验详解》ANTLR是一个强大的解析器生成器,用于读取、处理、执行或翻译结构化文本或二进制文件,下面就跟随小编一起看看Java如何使用ANTLR4对Lua脚本... 目录什么是ANTLR?第一个例子ANTLR4 的工作流程Lua脚本语法校验准备一个Lua Gramm

Java字符串操作技巧之语法、示例与应用场景分析

《Java字符串操作技巧之语法、示例与应用场景分析》在Java算法题和日常开发中,字符串处理是必备的核心技能,本文全面梳理Java中字符串的常用操作语法,结合代码示例、应用场景和避坑指南,可快速掌握字... 目录引言1. 基础操作1.1 创建字符串1.2 获取长度1.3 访问字符2. 字符串处理2.1 子字

Java Optional的使用技巧与最佳实践

《JavaOptional的使用技巧与最佳实践》在Java中,Optional是用于优雅处理null的容器类,其核心目标是显式提醒开发者处理空值场景,避免NullPointerExce... 目录一、Optional 的核心用途二、使用技巧与最佳实践三、常见误区与反模式四、替代方案与扩展五、总结在 Java

基于Java实现回调监听工具类

《基于Java实现回调监听工具类》这篇文章主要为大家详细介绍了如何基于Java实现一个回调监听工具类,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录监听接口类 Listenable实际用法打印结果首先,会用到 函数式接口 Consumer, 通过这个可以解耦回调方法,下面先写一个

使用Java将DOCX文档解析为Markdown文档的代码实现

《使用Java将DOCX文档解析为Markdown文档的代码实现》在现代文档处理中,Markdown(MD)因其简洁的语法和良好的可读性,逐渐成为开发者、技术写作者和内容创作者的首选格式,然而,许多文... 目录引言1. 工具和库介绍2. 安装依赖库3. 使用Apache POI解析DOCX文档4. 将解析

Qt中QUndoView控件的具体使用

《Qt中QUndoView控件的具体使用》QUndoView是Qt框架中用于可视化显示QUndoStack内容的控件,本文主要介绍了Qt中QUndoView控件的具体使用,具有一定的参考价值,感兴趣的... 目录引言一、QUndoView 的用途二、工作原理三、 如何与 QUnDOStack 配合使用四、自

Java字符串处理全解析(String、StringBuilder与StringBuffer)

《Java字符串处理全解析(String、StringBuilder与StringBuffer)》:本文主要介绍Java字符串处理全解析(String、StringBuilder与StringBu... 目录Java字符串处理全解析:String、StringBuilder与StringBuffer一、St

C++使用printf语句实现进制转换的示例代码

《C++使用printf语句实现进制转换的示例代码》在C语言中,printf函数可以直接实现部分进制转换功能,通过格式说明符(formatspecifier)快速输出不同进制的数值,下面给大家分享C+... 目录一、printf 原生支持的进制转换1. 十进制、八进制、十六进制转换2. 显示进制前缀3. 指

springboot整合阿里云百炼DeepSeek实现sse流式打印的操作方法

《springboot整合阿里云百炼DeepSeek实现sse流式打印的操作方法》:本文主要介绍springboot整合阿里云百炼DeepSeek实现sse流式打印,本文给大家介绍的非常详细,对大... 目录1.开通阿里云百炼,获取到key2.新建SpringBoot项目3.工具类4.启动类5.测试类6.测