gpt4 book ai didi

java - Spring数据 Cassandra : How to query tables with compound keys?

转载 作者:行者123 更新时间:2023-12-02 07:28:33 26 4
gpt4 key购买 nike

我有以下列族:

@Table(value = "request_event")
public class RequestEvent {

@PrimaryKeyColumn(name = "day_requested", ordinal = 0, type = PrimaryKeyType.PARTITIONED)
private LocalDate dayRequested;

@PrimaryKeyColumn(name = "date_requested", ordinal = 1, type = PrimaryKeyType.CLUSTERED, ordering = Ordering.DESCENDING)
private LocalDateTime dateRequested;

...
}

由存储库存储和访问:

@Repository
public interface RequestEventRepository extends CrudRepository<RequestEvent, LocalDateTime> {
}

不幸的是,requestEventRepository.findOne(localDate) 抛出异常,可能是因为它返回多个结果。我怎样才能解决这个问题?另外,如何检索特定日期的所有结果?

最佳答案

您有两种选择来使用 Spring Data Cassandra 表示复合键:

  1. 在域类型中使用 @PrimaryKeyColumn(就像您所做的那样)。
  2. 使用 @PrimaryKeyClass 表示主键并将其嵌入域类型中。

Spring Data 存储库接受单个 ID 类型。因此不可能仅将 LocalDateTime 声明为 id。如果您想在域类型中坚持使用 @PrimaryKeyColumn,请使用 MapId 作为 id 类型:

@Table(value = "request_event")
public class RequestEvent {

@PrimaryKeyColumn(name = "day_requested", ordinal = 0,
type = PrimaryKeyType.PARTITIONED)
private LocalDate dayRequested;

@PrimaryKeyColumn(name = "date_requested", ordinal = 1, type = PrimaryKeyType.CLUSTERED,
ordering = Ordering.DESCENDING)
private LocalDateTime dateRequested;

}

public interface RequestEventRepository extends CrudRepository<RequestEvent, MapId> {}

MapId mapId = BasicMapId.id("dayRequested", …).with("dateRequested", …);

RequestEvent loaded = eventRepository.findOne(mapId);

如果您决定将主键表示为值对象,则需要稍微调整域类型:

@PrimaryKeyClass
public class Key implements Serializable {

@PrimaryKeyColumn(name = "day_requested", ordinal = 0,
type = PrimaryKeyType.PARTITIONED)
private LocalDate dayRequested;

@PrimaryKeyColumn(name = "date_requested", ordinal = 1, type = PrimaryKeyType.CLUSTERED,
ordering = Ordering.DESCENDING)
private LocalDateTime dateRequested;

}

@Table(value = "request_event")
public class RequestEvent {

@PrimaryKey
private Key key;

}

public interface RequestEventRepository extends CrudRepository<RequestEvent, Key> {}

eventRepository.findOne(new Key(…))

关于java - Spring数据 Cassandra : How to query tables with compound keys?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44468888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com