使用Jongo使用空字段在MongoDB中保存POJO

时间:2014-10-14 10:00:16

标签: mongodb null jongo

所以我有一个POJO对象,我正在创建并使用Jongo保存到MongoDB集合:

import java.util.Map;

public class MyObject {

    private String name;
    private Map<String, String> mappings;

    public MyObject() {

    }

    public MyObject(String name, Map mappings) {
        this.name = name;
        this.mappings = mappings;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Map<String, String> getMappings() {
        return mappings;
    }

    public void setMappings(Map<String, String> mappings) {
        this.mappings = mappings;
    }
}

将对象保存到mongo的测试类:

import com.mongodb.DB;
import com.mongodb.MongoClient;
import org.jongo.Jongo;
import org.jongo.MongoCollection;

import java.net.UnknownHostException;
import java.util.HashMap;

public class NullFieldTest {

    public static void main(String[] args) throws UnknownHostException {

        DB db = new MongoClient("localhost", 27017).getDB("testDB") ;
        Jongo jongo = new Jongo(db);
        MongoCollection testCollection = jongo.getCollection("testCollection");

        MyObject objectA = new MyObject("objectA", new HashMap());
        MyObject objectB = new MyObject("objectB", null);

        testCollection.save(objectA);
        testCollection.save(objectB);

    }
}

此测试可以保存对象:

{
    "_id" : ObjectId("543cf1a6cd8936deafcf66cf"),
    "name" : "objectA",
    "mappings" : {}
}
{
    "_id" : ObjectId("543cf1a6cd8936deafcf66d0"),
    "name" : "objectB"
}

但我真正想要的是objectB中的空映射显示为

"mappings" : null

我知道集合中的字段可以具有空值,但我不知道如何使用jongo驱动程序,任何想法?

仅供参考,我使用的是jongo V1.1

2 个答案:

答案 0 :(得分:2)

问题解决了,我的问题在于对象的序列化,从Jackson添加了一个注释,甚至包括空字段:

@JsonInclude(JsonInclude.Include.ALWAYS)
public class MyObject {

在这篇文章中找到更多细节: How to tell Jackson to ignore a field during serialization if its value is null?

答案 1 :(得分:0)

Jongo带有一个预配置的Jackson,它忽略了空字段:https://github.com/bguerout/jongo/blob/443b461e47acdcffb9f51efafb291b7e0c805c26/src/main/java/org/jongo/marshall/jackson/configuration/VisibilityModifier.java

您可以使用JacksonMapper.Builder创建自定义Mapper来更改此配置:

Mapper mapper = new JacksonMapper.Builder().addModifier(new MapperModifier() {
    public void modify(ObjectMapper mapper) {
        mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
    }
}).build();
Jongo jongo = new Jongo(db, mapper);