You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB Java驱动3.11:@Discriminator缺失及与@BsonDiscriminator的疑问

Clarification on @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:

  1. 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
    }
    
  2. Customize discriminator values for subclasses (optional)
    By default, the discriminator field (named _t by default) will use the simple class name. You can override this with the value parameter:

    import org.bson.codecs.pojo.annotations.BsonDiscriminator;
    
    @BsonDiscriminator(value = "domestic_dog")
    public class Dog extends Animal {
        private String breed;
    
        // Constructors, getters, setters
    }
    
  3. Ensure you have the right dependency
    Make sure your build includes the bson module (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 22:27:31