1 | initial version |
Yes, Spring Data for MongoDB can return null instead of an empty entity field by setting the useNullInsteadOfEmpty
property to true in the MongoTemplate
.
For example, in your MongoConfiguration
class, you can add the following:
@Configuration
@EnableMongoRepositories(basePackages = "com.example.repository")
public class MongoConfiguration extends AbstractMongoConfiguration {
@Override
public MongoClient mongoClient() {
return new MongoClient("localhost",27017);
}
@Override
protected String getDatabaseName() {
return "myDatabase";
}
@Bean
public MongoTemplate mongoTemplate() {
MappingMongoConverter converter = new MappingMongoConverter(mongoDbFactory(), new MongoMappingContext());
converter.setMapKeyDotReplacement("_");
converter.setUseNullInsteadOfEmpty(true); // set this to true
return new MongoTemplate(mongoDbFactory(), converter);
}
}
With this configuration, any empty entity fields will be returned as null when querying from the database.