有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javapojo到org。布森。文件,反之亦然

有没有一种简单的方法可以将简单的POJO转换为org。布森。文件

我知道有这样的方法:

Document doc = new Document();
doc.append("name", person.getName()):

但它是否有一种更简单、打字更少的方式呢


共 (6) 个答案

  1. # 1 楼答案

    目前,Mongo Java驱动程序3.9.1提供了现成的POJO支持
    http://mongodb.github.io/mongo-java-driver/3.9/driver/getting-started/quick-start-pojo/
    假设您有这样一个示例集合,其中包含一个嵌套对象

    db.createCollection("product", {
    validator: {
        $jsonSchema: {
            bsonType: "object",
            required: ["name", "description", "thumb"],
            properties: {
                name: {
                    bsonType: "string",
                    description: "product - name - string"
                },
                description: {
                    bsonType: "string",
                    description: "product - description - string"
                },
                thumb: {
                    bsonType: "object",
                    required: ["width", "height", "url"],
                    properties: {
                        width: {
                            bsonType: "int",
                            description: "product - thumb - width"
                        },
                        height: {
                            bsonType: "int",
                            description: "product - thumb - height"
                        },
                        url: {
                            bsonType: "string",
                            description: "product - thumb - url"
                        }
                    }
                }
    
            }
        }
    }});
    

    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。为您的POJO添加注释

    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并获取POJO

    MongoCollection<Document> collection = mongoDatabase.getCollection("product");
    Document query = new Document();
    List<ProductEntity> products = collection.find(query, ProductEntity.class).into(new ArrayList<>());
    


    就这样!!!您可以轻松获得您的POJO 没有繁琐的手动映射 并且不丧失运行本机mongo查询的能力

  2. # 2 楼答案

    关键是,你不需要把手放在组织上。布森。文件

    莫菲娅会在幕后为你做这一切

    import com.mongodb.MongoClient;
    import org.mongodb.morphia.Datastore;
    import org.mongodb.morphia.DatastoreImpl;
    import org.mongodb.morphia.Morphia;
    import java.net.UnknownHostException;
    
    .....
        private Datastore createDataStore() throws UnknownHostException {
            MongoClient client = new MongoClient("localhost", 27017);
            // create morphia and map classes
            Morphia morphia = new Morphia();
            morphia.map(FooBar.class);
            return new DatastoreImpl(morphia, client, "testmongo");
        }
    
    ......
    
        //with the Datastore from above you can save any mapped class to mongo
        Datastore datastore;
        final FooBar fb = new FooBar("hello", "world");
        datastore.save(fb);
    

    这里有几个例子:https://mongodb.github.io/morphia/

  3. # 3 楼答案

    如果将Spring数据MongoDB与springboot结合使用,MongoTemplate有一种方法可以很好地做到这一点

    Spring Data MongoDB API

    这是一个样品

    一,。首先在spring boot项目中自动连接mongoTemplate

    @Autowired
    MongoTemplate mongoTemplate;
    

    二,。在您的服务中使用mongoTemplate

    Document doc = new Document();
    mongoTemplate.getConverter().write(person, doc);
    

    为此,需要配置pom文件和yml以注入mongotemplate

    波姆。xml

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>2.1.10.RELEASE</version>
    </dependency>
    

    应用程序。yml

    # mongodb config
    spring:
      data:
        mongodb:
          uri: mongodb://your-mongodb-url
    
  4. # 4 楼答案

    如果您使用的是Morphia,那么可以使用这段代码将POJO转换为文档

    Document document = Document.parse( morphia.toDBObject( Entity ).toString() )
    

    如果您没有使用Morphia,那么您可以通过编写自定义映射并将POJO转换为DBObject,然后将DBObject进一步转换为字符串,然后对其进行解析来执行相同的操作

  5. # 5 楼答案

    我不知道你的MongoDB版本。但现在,不需要将文档转换为POJO,也不需要将文档转换为POJO。您只需根据需要使用的文档或POJO创建集合,如下所示

    //If you want to use Document
    MongoCollection<Document> myCollection = db.getCollection("mongoCollection");
    Document doc=new Document();
    doc.put("name","ABC");
    myCollection.insertOne(doc);
    
    
    //If you want to use POJO
    MongoCollection<Pojo> myCollection = db.getCollection("mongoCollection",Pojo.class);
    Pojo obj= new Pojo();
    obj.setName("ABC");
    myCollection.insertOne(obj);
    

    如果要使用POJO,请确保您的Mongo DB配置了正确的codecregistry

    MongoClient mongoClient = new MongoClient();
    //This registry is required for your Mongo document to POJO conversion
    CodecRegistry codecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
            fromProviders(PojoCodecProvider.builder().automatic(true).build()));
    MongoDatabase db = mongoClient.getDatabase("mydb").withCodecRegistry(codecRegistry);
    
  6. # 6 楼答案

    您可以使用GsonDocument.parse(String json)将POJO转换为Document。这适用于java驱动程序的3.4.2版本

    大概是这样的:

    package com.jacobcs;
    
    import org.bson.Document;
    
    import com.google.gson.Gson;
    import com.mongodb.MongoClient;
    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.MongoDatabase;
    
    public class MongoLabs {
    
        public static void main(String[] args) {
            // create client and connect to db
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            MongoDatabase database = mongoClient.getDatabase("my_db_name");
    
            // populate pojo
            MyPOJO myPOJO = new MyPOJO();
            myPOJO.setName("MyName");
            myPOJO.setAge("26");
    
            // convert pojo to json using Gson and parse using Document.parse()
            Gson gson = new Gson();
            MongoCollection<Document> collection = database.getCollection("my_collection_name");
            Document document = Document.parse(gson.toJson(myPOJO));
            collection.insertOne(document);
        }
    
    }