Java连接,操作MongoDB

java连接MongoDB非常的简单,具体来说就2步:
1:向新建的工程中导入java-mongo的驱动包
如图:
这里写图片描述
2:建立一个链接帮助类,完成链接操作

package com.yc.mongodb;
import java.util.Iterator;
import java.util.Set;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.WriteResult;

public class MongoLink2 {

    public static void main(String[] args) {
        Mongo mongo=null;
        DB db=null;
        try {
            //链接mongo服务器
            mongo=new Mongo("127.0.0.1",27017);

            //根据mongodb数据库的名称获得DB对象,连接数据库yc
            db=mongo.getDB("yc");
            //发送获得请求
            db.requestStart();
            //获得其集合
            Set<String> collections=db.getCollectionNames();
            Iterator itr=collections.iterator();
            //迭代输出信息
            while(itr.hasNext()){
                System.out.println(itr.next());
            }

            DBCollection dbObject=db.getCollection("yc");
            DBObject object=null;
            //添加
            object=new BasicDBObject();
            object.put("_id", 1003);
            object.put("name","张三");
            object.put("sex","男");
            WriteResult rs=dbObject.insert(object);
            object.put("_id", 1002);
            //移除
            dbObject.remove(new BasicDBObject());
            //查询所有
            DBCursor cursor=dbObject.find();
            while(cursor.hasNext()){
                object=cursor.next();
                System.out.println(object);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(mongo!=null){
                mongo.close();
            }
        }
    }
}

运行的结果如下:
这里写图片描述
至此,其实已经可以使用,代码的耦合太高,功能捆绑的太严重,不方便调用,
接着对其进行封装。

先定义一个属性文件:
这里写图片描述
里面定义了一些基本的配置,例如用户名,数据库名,ip,端口等。
接着定义一个类去读取其文件.这里文件的话最好被定义为单例,

package com.yc.mongodb;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@SuppressWarnings("serial")
public class MyPro extends Properties{

    private static MyPro instanece=new MyPro();

    private MyPro(){
        InputStream is=MyPro.class.getResourceAsStream("/db.properties");
        try {
            this.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static MyPro getInstance(){
        return instanece;
    }

}

像操作oracle一样定义一个DBHelper类,实现对数据操作的封装:
如下:

package com.yc.mongodb;

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class DBHelper {
    private static Mongo mongo=null;
    private DB db=null;
    private DBCollection collection=null;

    static{
            try {
                mongo=new Mongo(MyPro.getInstance().getProperty("ip"),Integer.parseInt(MyPro.getInstance().getProperty("port")));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (MongoException e) {
                e.printStackTrace();
            }
            System.out.println(mongo);
    }

    /**
     * 
     * @param dbName
     * @param name
     * @param pwd
     * @return
     */
    public boolean getDB(String dbName,String name,String pwd){
        db=mongo.getDB(dbName);
        if(name!=null&&!"".equals(name)&&pwd!=null&&!"".equals(pwd)){
            if(db.authenticate(name, pwd.toCharArray())){
                return true;
            }else{
                return false;
            }
        }else{
            //查看配置文件中是否给定了用户名和密码
            String uname=MyPro.getInstance().getProperty("uname");
            String pwds=MyPro.getInstance().getProperty("password");
            if(uname!=null&&!"".equals(uname)&&pwds!=null&&!"".equals(pwds)){
                if(db.authenticate(uname, pwds.toCharArray())){
                    return true;
                }else{
                    return false;
                }
            }
        }
        return true;
    }
    /**
     * 关闭连接
     * @param mongo
     */
    public void closeAll(Mongo mongo){
        if(mongo!=null){
            mongo.close();
        }
    }

}
//利用方法重载实现不同情况的传参
/**
     * 获取指定的集合
     * @param collectionName :要链接的集合
     * @param dbName:集合所在的数据库
     * @return
     */
    public DBCollection getDBCollection(String collectionName,String dbName){
        DBCollection dBCollection=null;
        if(getDB(dbName,null, null)){
            db.requestStart();
            if(collectionName==null){//如果为空则从配置文件中查找
                collectionName=MyPro.getInstance().getProperty("collectionName");
            }
            dBCollection=db.getCollection(collectionName);
        }else{
            //抛出异常
            throw new RuntimeException("数据库连接失败");
        }
        return dBCollection;
    }
    /**
     * 
     * @param collectionName
     * @param dbName
     * @param name
     * @param password
     * @return
     */
    public DBCollection getDBCollection(String collectionName,String dbName,String name,String password){
        DBCollection dBCollection=null;
        if(getDB(dbName,name, password)){
            db.requestStart();
            if(collectionName==null){//如果为空则从配置文件中查找
                collectionName=MyPro.getInstance().getProperty("collectionName");
            }
            dBCollection=db.getCollection(collectionName);
        }else{
            //抛出异常
            throw new RuntimeException("数据库连接失败");
        }
        return dBCollection;
    }
    /**
     * 只传递集合名字
     * @param collectionName
     * @return
     */
    public DBCollection getDBCollection(String collectionName){
        DBCollection dBCollection=null;
        String dbName=MyPro.getInstance().getProperty("dbName");
        if(getDB(dbName,null, null)){
            db.requestStart();
            if(collectionName==null){//如果为空则从配置文件中查找
                collectionName=MyPro.getInstance().getProperty("collectionName");
            }
            dBCollection=db.getCollection(collectionName);
        }else{
            //抛出异常
            throw new RuntimeException("数据库连接失败");
        }
        return dBCollection;
    }
发布了50 篇原创文章 · 获赞 8 · 访问量 4万+
展开阅读全文

java项目连接mongoDB报错

08-14

在本地搭了环境,启动mongoDB数据库服务并进行了连接验证,如下: ![图片说明](https://img-ask.csdn.net/upload/201708/14/1502695838_396993.png) ![图片说明](https://img-ask.csdn.net/upload/201708/14/1502695905_168178.png) 启动eclipse,登录页面时会访问mongoDB,但总是连接超时,报错信息如下: org.springframework.dao.DataAccessResourceFailureException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=172.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}]; nested exception is com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=172.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}] at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:73) at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2002) at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1885) at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1696) at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1679) at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:598) at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:589) at com.jftt.wifi.service.impl.ManageUserServiceImpl.findUserByCondition(ManageUserServiceImpl.java:301) at com.jftt.wifi.service.impl.ManageUserServiceImpl.findUserByCondition(ManageUserServiceImpl.java:273) at com.jftt.wifi.service.impl.ManageUserServiceImpl.findUserByUserName(ManageUserServiceImpl.java:664) at com.jftt.wifi.action.LoginAction.login(LoginAction.java:369) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863) at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source) Caused by: com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=172.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}] at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:370) at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:101) at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75) at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71) at com.mongodb.binding.ClusterBinding.getReadConnectionSource(ClusterBinding.java:63) at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:166) at com.mongodb.operation.FindOperation.execute(FindOperation.java:394) at com.mongodb.operation.FindOperation.execute(FindOperation.java:57) at com.mongodb.Mongo.execute(Mongo.java:738) at com.mongodb.Mongo$2.execute(Mongo.java:725) at com.mongodb.DBCursor.initializeCursor(DBCursor.java:815) at com.mongodb.DBCursor.hasNext(DBCursor.java:149) at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1871) ... 49 more 请问各位大侠,有碰到这样的问题么?如何解决呢? 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览