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

  • 8
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值