1. 为 MongoDatabase bean 提供适当的 CodecRegistry
@Bean
public MongoClient mongoClient() {
ConnectionString connectionString = new ConnectionString("mongodb://username:password@127.0.0.1:27017/dbname");
ConnectionPoolSettings connectionPoolSettings = ConnectionPoolSettings.builder()
.minSize(2)
.maxSize(20)
.maxWaitQueueSize(100)
.maxConnectionIdleTime(60, TimeUnit.SECONDS)
.maxConnectionLifeTime(300, TimeUnit.SECONDS)
.build();
SocketSettings socketSettings = SocketSettings.builder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.build();
MongoClientSettings clientSettings = MongoClientSettings.builder()
.applyConnectionString(connectionString)
.applyToConnectionPoolSettings(builder -> builder.applySettings(connectionPoolSettings))
.applyToSocketSettings(builder -> builder.applySettings(socketSettings))
.build();
return MongoClients.create(clientSettings);
}
@Bean
public MongoDatabase mongoDatabase(MongoClient mongoClient) {
CodecRegistry defaultCodecRegistry = MongoClientSettings.getDefaultCodecRegistry();
CodecRegistry fromProvider = CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build());
CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(defaultCodecRegistry, fromProvider);
return mongoClient.getDatabase("dbname").withCodecRegistry(pojoCodecRegistry);
}
2.注释POJOS
public class ProductEntity {
@BsonProperty("name") public final String name;
@BsonProperty("description") public final String description;
@BsonProperty("thumb") public final ThumbEntity thumbEntity;
@BsonCreator
public ProductEntity(
@BsonProperty("name") String name,
@BsonProperty("description") String description,
@BsonProperty("thumb") ThumbEntity thumbEntity) {
this.name = name;
this.description = description;
this.thumbEntity = thumbEntity;
}
}
public class ThumbEntity {
@BsonProperty("width") public final Integer width;
@BsonProperty("height") public final Integer height;
@BsonProperty("url") public final String url;
@BsonCreator
public ThumbEntity(
@BsonProperty("width") Integer width,
@BsonProperty("height") Integer height,
@BsonProperty("url") String url) {
this.width = width;
this.height = height;
this.url = url;
}
}
3.查询mongoDB,获取POJOS
MongoCollection<Document> collection = mongoDatabase.getCollection("product");
Document query = new Document();
List<ProductEntity> products = collection.find(query, ProductEntity.class).into(new ArrayList<>());
请在其他
POJO 帖子中查看我对 org.bson.Document 和 Vice Versa的回答