Ask Your Question
2

Can Spring Data for MongoDB return null instead of an empty entity field?

asked 2023-07-12 09:18:03 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-07-12 09:24:02 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-12 09:18:03 +0000

Seen: 15 times

Last updated: Jul 12 '23