MongoDB Java驱动3.11:@Discriminator缺失及与@BsonDiscriminator的疑问
@Discriminator vs @BsonDiscriminator in MongoDB Java Driver 3.11 Great question—this is a common point of confusion thanks to a bit of shorthand in the official docs! Let me break it down clearly:
The Short Answer
In MongoDB Java Driver 3.11, there is no standalone @Discriminator annotation. The @Discriminator mentioned in the official docs is just a simplified reference to @BsonDiscriminator, which lives in the org.bson.codecs.pojo.annotations package (exactly the one you found in the Javadoc).
Why the Shorthand?
MongoDB's docs often use abbreviated names for their POJO annotations to make explanations flow better, but all actual annotation classes in the 3.11 driver follow the @Bson[Name] naming convention (think @BsonId, @BsonProperty, etc.). So when the docs say "add @Discriminator to your abstract class", they mean @BsonDiscriminator.
How to Use @BsonDiscriminator
Here's a quick example to enable discriminators for an inheritance hierarchy:
Annotate your abstract base class
This tells the codec to handle discriminator logic for all subclasses:import org.bson.codecs.pojo.annotations.BsonDiscriminator; @BsonDiscriminator public abstract class Animal { private String name; // Constructors, getters, setters }Customize discriminator values for subclasses (optional)
By default, the discriminator field (named_tby default) will use the simple class name. You can override this with thevalueparameter:import org.bson.codecs.pojo.annotations.BsonDiscriminator; @BsonDiscriminator(value = "domestic_dog") public class Dog extends Animal { private String breed; // Constructors, getters, setters }Ensure you have the right dependency
Make sure your build includes thebsonmodule (where the POJO annotations live). For Maven:<dependency> <groupId>org.mongodb</groupId> <artifactId>bson</artifactId> <version>3.11.0</version> </dependency>
When you serialize a Dog instance, MongoDB will store a _t field with the value domestic_dog (or the class name if you don't customize it), and when deserializing, the driver will use this field to instantiate the correct subclass.
内容的提问来源于stack exchange,提问作者P_M

