zoukankan      html  css  js  c++  java
  • 玩转mongodb(三):mongodb项目实战(初战)

    说明:

        主要功能:对mongodb的集合做增删改查。

        项目的运行环境:tomcat6、jdk8。

        所用技术:jsp/servlet、前端bootstrap。

        mongodb:personmap。

    mongodb工具类:

        定义一个MongoDBUtil的枚举类,枚举类中定义一个instance实例。

        MongoDB工具类 Mongo实例代表了一个数据库连接池,即使在多线程的环境中,一个Mongo实例对我们来说已经足够。
        注意Mongo已经实现了连接池,并且是线程安全的。
        设计为单例模式, 因 MongoDB的Java驱动是线程安全的,对于一般的应用,只要一个Mongo实例即可。
        Mongo有个内置的连接池(默认为10个) 对于有大量写和读的环境中,为了确保在一个Session中使用同一个DB时,DB和DBCollection是绝对线程安全的

    1 public enum MongoDBUtil {
    2     /**
    3      * 定义一个枚举的元素,它代表此类的一个实例
    4      */
    5     instance;
    6 }
    View Code

        在MongoDBUtil类中,定义一个MongoClient对象,并根据IP和端口获得该对象。

    1 private MongoClient mongoClient;
    2     static {
    3         System.out.println("===============MongoDBUtil初始化========================");
    4         // 从配置文件中获取属性值
    5         String ip = "localhost";
    6         int port = 27017;
    7         instance.mongoClient = new MongoClient(ip, port);
    8     }
    View Code

         根据MongoClient对象,得到MongoDataBase对象和MongoConnection<Document>对象。

     1  /**
     2      * 获取DB实例 - 指定DB
     3      * 
     4      * @param dbName
     5      * @return
     6      */
     7     public MongoDatabase getDB(String dbName) {
     8         if (dbName != null && !"".equals(dbName)) {
     9             MongoDatabase database = mongoClient.getDatabase(dbName);
    10             return database;
    11         }
    12         return null;
    13     }
    14     /**
    15      * 获取collection对象 - 指定Collection
    16      * 
    17      * @param collName
    18      * @return
    19      */
    20     public MongoCollection<Document> getCollection(String dbName, String collName) {
    21         if (null == collName || "".equals(collName)) {
    22             return null;
    23         }
    24         if (null == dbName || "".equals(dbName)) {
    25             return null;
    26         }
    27         MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName);
    28         return collection;
    29     }
    View Code

         工具类的查询、插入、更新、删除方法。

     1     /**条件查询*/
     2     public MongoCursor<Document> find(MongoCollection<Document> coll, Bson filter) {
     3         if(null!=filter){
     4             return coll.find(filter).iterator();
     5         }else{
     6             return coll.find().iterator();
     7         }
     8     }
     9     /**插入一条数据*/
    10     public void insert(MongoCollection<Document> coll,Document doc){
    11         coll.insertOne(doc);
    12     }
    13     
    14     /**更新一条数据*/
    15     public void update(MongoCollection<Document> coll,Document querydoc,Document updatedoc){
    16         coll.updateMany(querydoc, updatedoc);
    17     }
    18 
    19     /**删除一条数据*/
    20     public void delete(MongoCollection<Document> coll,Document doc){
    21         coll.deleteMany(doc);
    22     }
    View Code

     项目中的增删改查:

        插入:对应MongoDB中脚本的db.getCollection('person').insert({"name":"ryan1","age":21})

     1     String name = request.getParameter("name");
     2     Double age = Double.valueOf(request.getParameter("age"));
     3     
     4     String dbName = "personmap";
     5         String collName = "person";
     6         MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName);
     7         
     8         Document doc = new Document();
     9         doc.put("name", name);
    10         doc.put("age", age);
    11         MongoDBUtil.instance.insert(coll, doc);
    12         
    13         PrintWriter out = response.getWriter();
    14         out.write("insert success!");
    插入功能的servlet
     1 <div class="panel    panel-warning" style="20%">
     2     <div class="panel-heading">删除文档</div>
     3     <div class="panel-body">
     4         <form action="InsertPerson">
     5             <input type="text" name="name" class="form-control" placeholder="name" aria-describedby="basic-addon1">
     6             <br/>
     7             <input type="text" name="age" class="form-control" placeholder="age" aria-describedby="basic-addon1">
     8             <br/>
     9             <button type="submit" class="btn btn-default">插入</button>
    10         </form>
    11     </div>
    12 </div>
    插入功能的jsp

        

        更新:对应MongoDB中脚本的db.getCollection('person').update({"name":"ryan1"}{"$set":{"age":22}})

     1     String queryname = request.getParameter("queryname");
     2     Double updateage = Double.valueOf(request.getParameter("updateage"));
     3     
     4     String dbName = "personmap";
     5     String collName = "person";
     6     MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName);
     7         
     8     Document querydoc = new Document();
     9     querydoc.put("name", queryname);
    10 
    11     Document updatedoc = new Document();
    12     updatedoc.put("name", queryname);
    13     updatedoc.put("age", updateage);
    14                 
    15     MongoDBUtil.instance.update(coll, querydoc , new Document("$set",updatedoc));
    16         
    17         PrintWriter out = response.getWriter();
    18         out.write("update success!");
    更新功能的servlet
     1 <div class="panel    panel-warning" style="20%">
     2     <div class="panel-heading">根据name更新age</div>
     3     <div class="panel-body">
     4         <form action="UpdatePerson">
     5             <input type="text" name="queryname" class="form-control" placeholder="queryname" aria-describedby="basic-addon1">
     6             <br/>
     7             <input type="text" name="updateage" class="form-control" placeholder="updateage" aria-describedby="basic-addon1">
     8             <br/>
     9             <button type="submit" class="btn btn-default">更新</button>
    10     </form>
    11     </div>
    12 </div>
    更新功能的jsp

        

        删除:对应MongoDB中脚本的db.getCollection('person').remove({"name":"ryan1"})

     1     String name = request.getParameter("name");
     2     
     3     String dbName = "personmap";
     4     String collName = "person";
     5     MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName);
     6         
     7     Document doc = new Document();
     8     doc.put("name", name);
     9 
    10     MongoDBUtil.instance.delete(coll, doc);
    11         
    12     PrintWriter out = response.getWriter();
    13     out.write("delete success!");
    删除功能的servlet
     1 <div class="panel    panel-warning" style="20%">
     2     <div class="panel-heading">删除文档</div>
     3     <div class="panel-body">
     4         <form action="DeletePerson">
     5             <input type="text" name="name" class="form-control" placeholder="name" aria-describedby="basic-addon1">
     6             <br/>
     7             <button type="submit" class="btn btn-default">删除</button>
     8         </form>
     9     </div>
    10 </div>
    删除功能的jsp

        

        查找:对应MongoDB中脚本的db.getCollection('person').find({})

     1     String dbName = "personmap";
     2     String collName = "person";
     3     MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName);
     4         
     5     List<Person> personList = new ArrayList<Person>();
     6     // 查询所有
     7     //Bson filter = Filters.eq("name", "ryan1");
     8     Bson filter = null;
     9     MongoCursor<Document> cursor = MongoDBUtil.instance.find(coll, filter);
    10     while(cursor.hasNext()){
    11         Document tempdoc = cursor.next();
    12         Person person = new Person();
    13         person.set_id(tempdoc.get("_id").toString());
    14         person.setName(tempdoc.get("name").toString());
    15 person.setAge(Double.valueOf(tempdoc.get("age").toString()));
    16             personList.add(person);
    17     }
    18         
    19     Gson gson = new Gson();
    20         
    21     PrintWriter out = response.getWriter();
    22     out.write(gson.toJson(personList));
    查找功能的servlet
     1 <div class="panel panel-warning" style="50%">
     2     <div class="panel-heading">查找全部数据</div>
     3     <div class="panel-body">
     4     <table data-toggle="table" 
     5                data-url="FindPerson"
     6                data-classes="table table-hover table-condensed"
     7                data-striped="true">
     8         <thead>
     9             <tr>
    10                 <th class="col-xs-2" data-field="_id">_id</th>
    11                 <th class="col-xs-2" data-field="name">name</th>
    12                 <th class="col-xs-2" data-field="age">age</th>
    13             </tr>
    14         </thead>
    15     </table>
    16     </div>
    17 </div>
    查找功能的jsp

        

        源代码下载

      喜欢请微信扫描下面二维码,关注我公众号--“精修Java”,做一些实战项目中的问题和解决方案分享。 

  • 相关阅读:
    Oracle性能调整ASH,AWR,ADDM
    子网掩码、子网划分详解
    10046事件sql_trace跟踪
    find详解
    date详解
    touch详解
    [转]lsof详解
    iftop、ifstat详解
    iotop详解
    关于Unity的入门游戏飞机大战的开发(上)
  • 原文地址:https://www.cnblogs.com/zhouqinxiong/p/5548156.html
Copyright © 2011-2022 走看看