MongoDB動態建表方案(官方原生驅動)
需求前提:表名動態,表結構靜態,庫固定
1.匯入相關依賴
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.11.2</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>3.11.2</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-core</artifactId>
<version>3.11.2</version>
</dependency>
2.定義物體
@Data
public class Person {
private String name;
private int sex;
private String address;
}
3.設定物體決議器
public static void addMongoDB(String collectionName) {
CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build()));
MongoClient mongoClient = MongoClients.create("mongodb://admin:Tong#[email protected]:15700");
//指定物體決議器
MongoDatabase mongoDatabase = mongoClient.getDatabase("marty_test").withCodecRegistry(pojoCodecRegistry);
MongoCollection<Person> mongoCollection = mongoDatabase.getCollection(collectionName, Person.class);
Person person = new Person();
person.setName("test");
person.setAddress("地址");
person.setSex(1);
mongoCollection.insertOne(person);
}
說明:Collection獲取之后,第一次插入資料時,會自動創建,Database也類似
4.測驗
public static void main(String[] args) throws Exception {
for (int i = 0; i < 10; i++) {
addMongoDB("test-" + i);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/227148.html
標籤:其他
上一篇:2020年MySQL資料庫面試題總結(50道題含答案決議)
下一篇:Redis 常見問題總結
