使用 Cassandra 的 Datastax 实体映射器时如何使用继承?

How do I use inheritance when using the Datastax entity mapper for Cassandra?

我尝试使用 Cassandra 来持久化非常简单的 POJO,但使用 class 层次结构(许多子classes,一个超级class)。我正在使用 Java 和 Datastax 驱动程序(以及对象映射器)。

我的问题是对象映射器似乎无法识别在 superclasses 中注释的字段。

我实现的结构是:

@Table(keyspace = "...", name = "...")
public class Subclass extends Superclass {  
    public double x;
    public double y;
    public double z;

   ....
}

public class Superclass {   
    @PartitionKey(0)
    @Column(name = "user_id")
    public long userId;

    @PartitionKey(1)
    @Column(name = "device_id")
    public long deviceId;
}

然后我尝试保存 Subclass 个对象:

public static void main(String[] args) {
    Subclass data = new Subclass();
    data.deviceId = 123;
    data.userId = 1212;
    data.x = 0;
    data.y = 1;
    data.z = 2;

    Cluster cluster;
    Session session;

    ...

    Mapper<Subclass> mapper = new MappingManager(session).mapper(Subclass.class);

    mapper.save(data);
}

这抛出:

 com.datastax.driver.core.exceptions.InvalidQueryException: Missing mandatory PRIMARY KEY part user_id

有什么方法可以在这样的结构中得到它运行?一种解决方案是在 subclass 中重新声明 userId / deviceID 字段,但这会非常难看(很多重复代码)。关于如何为此类案例归档良好结构或最佳实践的任何想法?

更新: 从 3.1.0 版开始,驱动程序现在支持继承,如问题中所述。有关详细信息,请参阅 Polymorphism Support section of the driver manual

When mapping an entity class or a UDT class, the mapper will transparently scan superclasses and superinterfaces for annotations on fields and getter methods, thus enabling the polymorphic mapping of one class hierarchy into different CQL tables or UDTs.

Java 驱动程序 4.1.0+ 也将支持实体和 daos 的继承。

原答案:

很遗憾,您目前无法执行此操作。您需要创建两个具有重复结构的单独 类。如果您想以通用方式处理两个实现的对象,您可以创建一个带有共享字段的接口。

有一张票 JAVA-541 添加对此的支持,如果您想在驱动程序中看到此功能,请投票。