Java – spring data Cassandra: how to use composite keys to query tables?
I have the following families:
@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;
...
}
Stored and accessed by the repository:
@Repository
public interface RequestEventRepository extends CrudRepository<RequestEvent,LocalDateTime> {
}
Unfortunately, requesteventrepository Findone (localdate) throws an exception, possibly because it returns multiple results How can I solve this problem? In addition, how do I retrieve all results for a specific date?
Solution
You have two options to represent the composite key of spring data Cassandra:
>Use @ primarykeycolumn in the domain type (just like you). > Use @ primarykeyclass to represent the primary key and embed it in the domain type
The spring data repository accepts a single ID type Therefore, it is impossible to declare only localdatetime as ID. if you want to adhere to @ primarykeycolumn in the domain type, please use mapid as the ID type:
@Table(value = "request_event")
public class RequestEvent {
@PrimaryKeyColumn(name = "day_requested",type = PrimaryKeyType.PARTITIONED)
private LocalDate dayRequested;
@PrimaryKeyColumn(name = "date_requested",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);
If you decide to represent the primary key as a value object, you need to adjust the domain type slightly:
@PrimaryKeyClass
public class Key implements Serializable {
@PrimaryKeyColumn(name = "day_requested",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(…))
