Skip to content

Instantly share code, notes, and snippets.

@laurentpellegrino
Created January 31, 2025 17:41
Show Gist options
  • Save laurentpellegrino/fe52138fe0ce6d28292e78fd30edea2d to your computer and use it in GitHub Desktop.
Save laurentpellegrino/fe52138fe0ce6d28292e78fd30edea2d to your computer and use it in GitHub Desktop.
Spring Data MongoDB without _class field on demand per class
package io.noticeable.data.autoconfigure;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NoTypeAlias {
}
package io.noticeable.data.autoconfigure;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
@Configuration
public class NoTypeAliasConfiguration {
private final ApplicationContext applicationContext;
@Autowired
public NoTypeAliasConfiguration(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@PostConstruct
public void init() {
final MappingMongoConverter converter = applicationContext.getBean(MappingMongoConverter.class);
final MongoMappingContext mappingContext = applicationContext.getBean(MongoMappingContext.class);
converter.setTypeMapper(new NoTypeAliasMongoTypeMapper(mappingContext));
}
}
package io.noticeable.data.autoconfigure;
import org.bson.conversions.Bson;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.util.TypeInformation;
public class NoTypeAliasMongoTypeMapper extends DefaultMongoTypeMapper {
public NoTypeAliasMongoTypeMapper(MongoMappingContext mappingContext) {
// Pass the mappingContext so alias resolution keep working
super(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY, mappingContext);
}
@Override
public void writeType(final TypeInformation<?> info, final Bson sink) {
// If the type is annotated with @NoTypeAlias, skip the _class field
if (info.getType().isAnnotationPresent(NoTypeAlias.class)) {
return;
}
// Otherwise, let the parent handle alias resolution
super.writeType(info, sink);
}
}
@laurentpellegrino
Copy link
Author

laurentpellegrino commented Jan 31, 2025

Then, you can use the annotation on your entity class as this:

@Document(collection = "publications")
@NoTypeAlias
public class Publication {
  // ...
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment