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#1234@168.1.121.4: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);
}
}