首页 > 解决方案 > Spring Data Firestore 中的外键/DBRef

问题描述

我有 2 个实体: 1- 用户:

@Document(collectionName = CollectionConstants.USER_COLLECTION)
public class User {
  @DocumentId
  protected String id;

  private String username;
}

2- 比赛:

@Document(collectionName = CollectionConstants.CONTEST_COLLECTION)
public class Contest {
  private List<User> contestants;
}

如何在让 Spring Data 自动管理的同时仅将用户的 ID(无论是用户列表还是单个用户)保存在数据库中?

我实际上正在寻找以下替代方案:

标签: springspring-bootgoogle-cloud-firestorespring-data

解决方案


我已经检查了Spring Cloud GCP for Firestore,它指出:

starter 在 Spring 应用程序上下文中自动配置和注册 Firestore bean。要开始使用它,只需使用@Autowired注释。

@Autowired
Firestore firestore;

void writeDocumentFromObject() throws ExecutionException, InterruptedException {
    // Add document data with id "joe" using a custom User class
    User data = new User("Joe",
            Arrays.asList(
                    new Phone(12345, PhoneType.CELL),
                    new Phone(54321, PhoneType.WORK)));

    // .get() blocks on response
    WriteResult writeResult = this.firestore.document("users/joe").set(data).get();

    LOGGER.info("Update time: " + writeResult.getUpdateTime());
}

User readDocumentToObject() throws ExecutionException, InterruptedException {
        ApiFuture<DocumentSnapshot> documentFuture =
                this.firestore.document("users/joe").get();

        User user = documentFuture.get().toObject(User.class);

        LOGGER.info("read: " + user);

        return user;
}

有示例https://github.com/spring-cloud-gcp/spring-cloud-gcp-samples/spring-cloud-gcp-firestore-sample


推荐阅读