1

我正在尝试将实体保存为 Mongodb 中的文档并尝试为其创建编解码器。它似乎不起作用。我尝试了 Morphia,但是我无法找到有关在运行时使用 morphia 在文档中添加额外字段的文档。这将违背首先使用 Mongodb 的基本目的。我最初希望我的文档在 POJO 中具有固定数量的字段。并且在应用程序运行期间,字段的数量应该改变

任何人都可以建议我该怎么做

4

1 回答 1

0

我不知道这是否是一个好的解决方案,但这就是我所做的。如果您不使用 Morphia for Mongodb 。并且您希望您的 POJO 实体被序列化。您可以像下面显示的代码那样执行此操作。但是如果你想组织下面的数据,你必须维护 setter 调用顺序是两个类,它给出了一些提示

package com.mongodbtest.entities;

 import java.io.Serializable;

 import org.bson.Document;

 import org.bson.BsonDocument;
 import org.bson.BsonInt32;
  import org.bson.BsonNumber;
 import org.bson.BsonString;

public class User extends BsonDocument {

/**
     * 
     */
private static final long serialVersionUID = -9167404209850672507L;
// private String _id;
private BsonString name;
private BsonString email;
private BsonString address;
private BsonInt32 phno;

public User(String name, String email, StringBuilder address, Number phno) {
    super();
    this.name = new BsonString(name);
    this.email = new BsonString(email);
    this.address = new BsonString(address.toString());
    this.phno = new BsonInt32(phno.intValue());
}

public User() {
}

public BsonString getName() {
    return this.name;
}

public void setName(String name) {
    this.name = new BsonString(name);
    this.append("name", this.name);

}

public BsonString getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = new BsonString(email);
    this.append("email", this.email);
}

public BsonString getAddress() {
    return address;
}

public void setAddress(StringBuilder address) {
    this.address = new BsonString(address.toString());
    this.append("address", this.address);
}

public BsonInt32 getPhno() {
    return phno;
}

public void setPhno(Number phno) {
    this.phno = new BsonInt32(phno.intValue());
    this.append("phno", this.phno);
}

}

并且序列化它的类将是这样的

package com.mongodb.sample;

import org.bson.BsonDocument;
import org.bson.Document;

import com.mogodbsample.config.DBconfig;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodbtest.entities.User;

public class Firstmongoaccess {

public static void main(String... args) {
    MongoDatabase dataase = DBconfig.getdatabase();
    MongoCollection<User> collection = dataase.getCollection("users",  User.class);

    User u1 = new User();
    u1.setAddress(new StringBuilder("something street bangalore 356322"));
    u1.setName("xxxxxx");
    u1.setEmail("gh@gmail.com");
    u1.setPhno(3263433);

    collection.insertOne(u1);
    MongoCursor<? extends BsonDocument> cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

}
}
于 2017-02-15T07:06:31.220 回答