mongodb—使用java继承加载了任意类类型的mongo数据

xhv8bpkk  于 2021-07-12  发布在  Java
关注(0)|答案(0)|浏览(219)

问题的背景如下:
我有两个类,一个父类(deliverylocation)和一个子类(returndeliverylocation),这些类是mongodb中的子文档表示。它们被定义为类中的字段,该类表示使用它们的主文档(manifestShipping),其类型为父类。

public class ManifestShipment extends MetadataDocument {

  @Id
  private ObjectId id;

  @Indexed(direction = IndexDirection.ASCENDING, name = "expeditionId_1")
  private ObjectId expeditionId;

  private Courier courier;

  private DeliveryLocation origin;

  private DeliveryLocation destination;

}
public class DeliveryLocation {

  private Integer id;

  public DeliveryLocationType getType() {
    return DeliveryLocationType.DEFAULT;
  }
}
public class ReturnDeliveryLocation extends DeliveryLocation {

  private DeliveryLocationType type = DeliveryLocationType.DEFAULT;

  private ReturnAddress location;
}

我总是使用子类存储数据。
当我将mongodb中的数据加载到主文档类中时,子文档有时以父类的类型加载,有时以子类的类型加载,我不知道原因。是因为这两个类都可以加载数据吗?为什么是随机的?如果我用两个不同的值定义字段“type”,一个用于父类,另一个用于子类(而不是都是“default”),那么数据将始终以子类的类型加载(这就是我想要的)。
使用的查询

public interface ManifestShipmentMongoRepository extends MongoRepository<ManifestShipment, ObjectId> {

  @Query(sort = "{'_metadata.createdAt': -1 }")
  ManifestShipment findFirstByExpeditionId(ObjectId expeditionId);

}

mongodb子文档中存储的数据

{
...
  "origin": {
    "type": "DEFAULT",
    "location": {
      "name": "Name1",
      "name2": "",
      "surname": ".",
      "address1": "Address",
      "city": "City",
      "province": "Province",
      "provinceIso": "PI",
      "zipCode": "-",
      "country": "Country",
      "countryIso": "CountryIso"
    },
    "_class": "ReturnDeliveryLocation"
  }
...
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题