MongoDB 项目集成(mongo-java-driver 3.4.1)

来源:互联网 发布:文明5 mac steam 汉化 编辑:程序博客网 时间:2024/04/29 13:19

工具类:

/** * mongodb工具类 * @author weixl */public final class Mongo {private static Logger logger = LoggerFactory.getLogger(Mongo.class);private static MongoClient mongoClient = null;private static ObjectMapper jsonMapper = new ObjectMapper();static{jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);}private Mongo(){}//初始化客户端private static MongoClient getClient(){try {if(null != mongoClient){return mongoClient;}//获取配置参数//String domains = SystemProperty.getProperyValue("mongo.domains");//String user = SystemProperty.getProperyValue("mongo.user");//String password = SystemProperty.getProperyValue("mongo.password");//String database = SystemProperty.getProperyValue("mongo.database");String domains = "dev.mongodb1.cnhz.shishike.com:3717;dev.mongodb2.cnhz.shishike.com:3717";String user = "weixl";String password = "123";String database = "test";//组装mongo服务端地址final List<ServerAddress> addressLists =new ArrayList<>();for(String domain : domains.split(";")){String[] hostAndPort = domain.split(":");String host = hostAndPort[0];String port = hostAndPort[1];ServerAddress serverAddress = new ServerAddress(host, Integer.parseInt(port));addressLists.add(serverAddress);}//组装mongo各项参数  默认值//maxConnectionsPerHost = 100;//threadsAllowedToBlockForConnectionMultiplier = 5;//serverSelectionTimeout = 1000 * 30;//maxWaitTime = 1000 * 60 * 2;//maxConnectionIdleTime;//maxConnectionLifeTime;//connectTimeout = 1000 * 10;//socketTimeout = 0;//socketKeepAlive = false;//sslEnabled = false;//sslInvalidHostNameAllowed = false;//alwaysUseMBeans = false;////heartbeatFrequency = 10000;//minHeartbeatFrequency = 500;//heartbeatConnectTimeout = 20000;//heartbeatSocketTimeout = 20000;//localThreshold = 15;final MongoClientOptions options = MongoClientOptions.builder().build();//组装权限对象final List<MongoCredential> credentialsLists = new ArrayList<>();MongoCredential credential = MongoCredential.createCredential(user, database, password.toCharArray());credentialsLists.add(credential);//创建客户端mongoClient = new MongoClient(addressLists, credentialsLists, options);} catch (Exception e) {logger.error("MongoDB init error",e);}return mongoClient;}private static MongoDatabase getDB(){//String database = SystemProperty.getProperyValue("mongo.database");String database = "calm_erp_dev";return getClient().getDatabase(database);}private static MongoCollection<Document> getCollection(String collName){return getDB().getCollection(collName);}/**----------------------------------------------------------CRUD-------------------------------------------------------------*//**-------------------------新增-----------------------------*//** * 新增一条记录 * @param obj * @throws JsonProcessingException  */public static void insert(MongoBaseObject bean) throws JsonProcessingException{notNull("bean", bean);List<MongoBaseObject> list = new ArrayList<>();list.add(bean);insert(list);}/** * 新增多条记录 * @param list * @throws JsonProcessingException  */public static void insert(List<? extends MongoBaseObject> list) throws JsonProcessingException{notNull("list", list);if(CollectionUtils.isNotEmpty(list)){String collName = null;List<Document> docList = new ArrayList<>();for(MongoBaseObject bean : list){if(null == collName){collName = bean.getClass().getSimpleName();}String json = jsonMapper.writeValueAsString(bean);Document doc = Document.parse(json);docList.add(doc);}MongoCollection<Document> coll = getCollection(collName);coll.insertMany(docList);}}/**-------------------------查询-----------------------------*//** * 查询集合所有文档 * @param  * @return * @throws IOException  * @throws JsonMappingException  * @throws JsonParseException  */public static <T extends MongoBaseObject> List<T> findAll(Class<T> clazz) throws JsonParseException, JsonMappingException, IOException{return find(null, clazz);}/** * 根据条件查询 * @param  * @return * @throws IOException  * @throws JsonMappingException  * @throws JsonParseException  */public static <T extends MongoBaseObject> List<T> find(Bson filter, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException{List<T> list = new ArrayList<>();String collName = clazz.getSimpleName();MongoCollection<Document> coll = getCollection(collName);FindIterable<Document> find = null == filter?coll.find():coll.find(filter);MongoCursor<Document> cursor = find.iterator();while(cursor.hasNext()){String json = cursor.next().toJson();T t = jsonMapper.readValue(json, clazz);list.add(t);}return list;}}

单元测试:

public class TestMongo {@Testpublic void testInsert() throws JsonProcessingException{Log log = new Log();log.set_id(UUIDUtil.getUUID());log.setOperateType("修改");Mongo.insert(log);}@Testpublic void testQueryList() throws JsonParseException, JsonMappingException, IOException{Bson filter = eq("operateType", "修改");List<Log> list = Mongo.find(filter, Log.class);}}


1 0
原创粉丝点击