Java POJO类直接存储在MongoDB中

记录Java POJO类直接存储在MongoDB中的策略。

 

maven:

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver</artifactId>
    <version>3.8.0</version>
</dependency>

 

Java POJO类定义:

public class DiagnoseDocument {
    private ObjectId id;
    private String time;
    private String instance;
    private ArrayList<DiagnsoeResult> result;
}


public class DiagnsoeResult {
    private String instance_name;
    private String rule_name;
    private String problem_level;
    private String problem_name;
    private String problem_detail;
    private String advice;
}

 

插入的方法:

//复制集连接MongoDB
String uriString = getURIString(primary);
// 需要针对对象中的类型设置Codec
CodecProvider pojoCodecProvider = PojoCodecProvider.builder().register(DiagnoseDocument.class, DiagnsoeResult.class).build();
CodecRegistry pojoCodecRegistry = fromRegistries(fromCodecs(new StringCodec(), new ObjectIdCodec(), new BsonArrayCodec()), fromProviders(pojoCodecProvider));
MongoClient mongoClient = new MongoClient(new MongoClientURI(uriString));
MongoDatabase database = mongoClient.getDatabase("mydb");
//对Collection中的类型设置Codec
MongoCollection<DiagnoseDocument> collection = database.getCollection("soar", DiagnoseDocument.class).withCodecRegistry(pojoCodecRegistry);
collection.insertOne(diagnoseDocument);

 

posted @ 2019-04-15 21:29  JayInnn  阅读(1260)  评论(0编辑  收藏  举报