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

相关文章

Spring Security常见问题及解决方案

《SpringSecurity常见问题及解决方案》SpringSecurity是Spring生态的安全框架,提供认证、授权及攻击防护,支持JWT、OAuth2集成,适用于保护Spring应用,需配置... 目录Spring Security 简介Spring Security 核心概念1. ​Securit

postgresql使用UUID函数的方法

《postgresql使用UUID函数的方法》本文给大家介绍postgresql使用UUID函数的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录PostgreSQL有两种生成uuid的方法。可以先通过sql查看是否已安装扩展函数,和可以安装的扩展函数

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF

SpringBoot改造MCP服务器的详细说明(StreamableHTTP 类型)

《SpringBoot改造MCP服务器的详细说明(StreamableHTTP类型)》本文介绍了SpringBoot如何实现MCPStreamableHTTP服务器,并且使用CherryStudio... 目录SpringBoot改造MCP服务器(StreamableHTTP)1 项目说明2 使用说明2.1

spring中的@MapperScan注解属性解析

《spring中的@MapperScan注解属性解析》@MapperScan是Spring集成MyBatis时自动扫描Mapper接口的注解,简化配置并支持多数据源,通过属性控制扫描路径和过滤条件,利... 目录一、核心功能与作用二、注解属性解析三、底层实现原理四、使用场景与最佳实践五、注意事项与常见问题六

Spring的RedisTemplate的json反序列泛型丢失问题解决

《Spring的RedisTemplate的json反序列泛型丢失问题解决》本文主要介绍了SpringRedisTemplate中使用JSON序列化时泛型信息丢失的问题及其提出三种解决方案,可以根据性... 目录背景解决方案方案一方案二方案三总结背景在使用RedisTemplate操作redis时我们针对

Java中Arrays类和Collections类常用方法示例详解

《Java中Arrays类和Collections类常用方法示例详解》本文总结了Java中Arrays和Collections类的常用方法,涵盖数组填充、排序、搜索、复制、列表转换等操作,帮助开发者高... 目录Arrays.fill()相关用法Arrays.toString()Arrays.sort()A

Spring Boot Maven 插件如何构建可执行 JAR 的核心配置

《SpringBootMaven插件如何构建可执行JAR的核心配置》SpringBoot核心Maven插件,用于生成可执行JAR/WAR,内置服务器简化部署,支持热部署、多环境配置及依赖管理... 目录前言一、插件的核心功能与目标1.1 插件的定位1.2 插件的 Goals(目标)1.3 插件定位1.4 核

如何使用Lombok进行spring 注入

《如何使用Lombok进行spring注入》本文介绍如何用Lombok简化Spring注入,推荐优先使用setter注入,通过注解自动生成getter/setter及构造器,减少冗余代码,提升开发效... Lombok为了开发环境简化代码,好处不用多说。spring 注入方式为2种,构造器注入和setter

MySQL中比较运算符的具体使用

《MySQL中比较运算符的具体使用》本文介绍了SQL中常用的符号类型和非符号类型运算符,符号类型运算符包括等于(=)、安全等于(=)、不等于(/!=)、大小比较(,=,,=)等,感兴趣的可以了解一下... 目录符号类型运算符1. 等于运算符=2. 安全等于运算符<=>3. 不等于运算符<>或!=4. 小于运