时间:2021-07-01 10:21:17 帮助过:28人阅读
2.封装mongoDBUtil工具类
1 //不通过认证获取连接数据库对象 2 public static MongoCollection<Document> getConnect(){ 3 //连接到 mongodb 服务 4 MongoClient mongoClient = new MongoClient("ip", 27017); 5 ? 6 //连接到数据库 7 MongoDatabase mongoDatabase = mongoClient.getDatabase("数据库名称"); 8 ? 9 //连接数据库表 10 MongoCollection<Document> personalData = mongoDatabase.getCollection("表名称"); 11 ? 12 //返回连接数据库表对象 13 return personalData; 14 } 15 ? 16 //需要密码认证方式连接 17 public static MongoCollection<Document> getConnect2(){ 18 List<ServerAddress> adds = new ArrayList<>(); 19 //ServerAddress()两个参数分别为 服务器地址 和 端口 20 ServerAddress serverAddress = new ServerAddress("localhost", 27017); 21 adds.add(serverAddress); 22 ? 23 List<MongoCredential> credentials = new ArrayList<>(); 24 //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码 25 MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray()); 26 credentials.add(mongoCredential); 27 ? 28 //通过连接认证获取MongoDB连接 29 MongoClient mongoClient = new MongoClient(adds, credentials); 30 ? 31 //连接到数据库 32 MongoDatabase mongoDatabase = mongoClient.getDatabase("test"); 33 ? 34 //连接数据库表 35 MongoCollection<Document> personalData = mongoDatabase.getCollection("表名"); 36 ? 37 //返回连接数据库对象 38 return personalData; 39 }
测试类
1 @Test 2 public void deom01(){ 3 MongoCollection<Document> connect = MongoDBUtil.getConnect(); 4 ? 5 JSONObject json = new JSONObject(); 6 json.put("111","hasidffhasedfhed"); 7 json.put("222","hasidffhasedfhed"); 8 json.put("333","hasidffhasedfhed"); 9 json.put("444","hasidffhasedfhed"); 10 json.put("5555","hasidffhasedfhed"); 11 Document json1 = new Document(json); 12 connect.insertOne(json1); 13 }
?
大家可以关注我的公众号秦川以北后续有更多精彩实用内容分享谢谢!
mongoDB数据库原生配置
标签:yum oca sha 工具类 pen family creates 应用 pre