2020-11-24

MongoDB动态建表方案(官方原生驱动)

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.定义实体

@Datapublic 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);  } }








原文转载:http://www.shaoqun.com/a/492933.html

转运中国:https://www.ikjzd.com/w/1549

好卖家:https://www.ikjzd.com/w/776

e邮宝:https://www.ikjzd.com/w/594.html?source=tagwish


MongoDB动态建表方案(官方原生驱动)需求前提:表名动态,表结构静态,库固定1.导入相关依赖<dependency><groupId>org.mongodb</groupId><artifactId>mongodb-driver</artifactId><version>3.11.2</version><
agora:agora
派代:派代
香港旅游酒店选择攻略 :香港旅游酒店选择攻略
新兴天露山梅花几月开?天露山梅花盛花期?:新兴天露山梅花几月开?天露山梅花盛花期?
东部华侨城水公园五一开放吗?华侨城水公园开放时间?:东部华侨城水公园五一开放吗?华侨城水公园开放时间?

No comments:

Post a Comment