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 Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件

Java中的数组与集合基本用法详解

《Java中的数组与集合基本用法详解》本文介绍了Java数组和集合框架的基础知识,数组部分涵盖了一维、二维及多维数组的声明、初始化、访问与遍历方法,以及Arrays类的常用操作,对Java数组与集合相... 目录一、Java数组基础1.1 数组结构概述1.2 一维数组1.2.1 声明与初始化1.2.2 访问

Javaee多线程之进程和线程之间的区别和联系(最新整理)

《Javaee多线程之进程和线程之间的区别和联系(最新整理)》进程是资源分配单位,线程是调度执行单位,共享资源更高效,创建线程五种方式:继承Thread、Runnable接口、匿名类、lambda,r... 目录进程和线程进程线程进程和线程的区别创建线程的五种写法继承Thread,重写run实现Runnab