user2066880
user2066880

Reputation: 5034

How to store null fields with Morphia

Morphia does not store null/empty fields by default. Is there a way to enable this?

Upvotes: 4

Views: 2684

Answers (3)

hc_dev
hc_dev

Reputation: 9377

To allow null or empty values for fields, you can configure the Mapper behavior trough MapperOptions, as already answered by evanchooly (main contributor to Morphia).

Use MapperOptions.Builder

Since version 2.0 use the MapperOptions.Builder for that. It has setter for both:

  • storeNulls(boolean)
  • storeEmpties(boolean)

Since Morphia version 2.0 the MapperOptions are immutable, but very powerful to control mapping-behavior. To store null or empty values build the mapper-options as follows:

String databaseName = "morphia_example";

MapperOptions options = MapperOptions.builder()
    .setStoreNulls(true)
    .setStoreEmpties(true)
    .build();

Datastore datastore = Morphia.createDatastore(databaseName, options)

See also

Upvotes: 0

evanchooly
evanchooly

Reputation: 6233

In the interests of answering the question asked, you can:

You can get a MapperOptions reference from the mapper instance by Mapper.getOptions().

Deprecation Update

However, the Mapper class is internal only and is deprecated:

this class will be internalized in 2.0

Same deprecation applies for before mentioned setter methods in class MapperOptions, instead the JavaDocs recommend:

use the Builder instead

Upvotes: 6

xeraa
xeraa

Reputation: 10859

This is a feature and one of the points of a document store. Don't waste space (both on RAM, disk, and for transfers) on missing data.

If you use primitive types instead of object types, a value will be saved, since there's no null value. For example long instead of Long. For String you'd need to store an empty (or some dummy) value.

Out of interest: Why would you want to explicitly store null / empty fields? Maybe there's a better solution for what you are trying to do.

Upvotes: 2

Related Questions