1. 程式人生 > >Java POJO類直接存儲在MongoDB中

Java POJO類直接存儲在MongoDB中

tid ava advice provider reg mongodb clas odata dep

記錄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);

Java POJO類直接存儲在MongoDB中