-
Create POJO that represents your composite key and provide converters for it:
CommentsKey.javaimport lombok.Value; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.ReadingConverter; import org.springframework.data.convert.WritingConverter; @Value public class CommentsKey { public final long pageId; public final long threadId; @WritingConverter public enum CommentsKeyToStringConverter implements Converter<CommentsKey, String> { INSTANCE; @Override public String convert(CommentsKey source) { return "comments::" + source.pageId + "::" + source.threadId; } } @ReadingConverter public enum StringToCommentsKeyConverter implements Converter<String, CommentsKey> { INSTANCE; @Override public CommentsKey convert(String source) { String[] split = source.split("::"); if (split.length != 3) { throw new IllegalArgumentException("Key can not be parsed: " + source); } long pageId = Long.parseLong(split[1]); long threadId = Long.parseLong(split[2]); return new CommentsKey(pageId, threadId); } } }
-
Use your custom key POJO in the document class:
CommentsDocument.javaimport lombok.AllArgsConstructor; import lombok.Builder; import lombok.Value; import org.springframework.data.aerospike.mapping.Document; import org.springframework.data.aerospike.mapping.Field; import org.springframework.data.annotation.Id; import java.util.List; @Value @Document(collection = "demo-service-comments-set") @Builder(toBuilder = true) @AllArgsConstructor// Spring Data object creation can use all-args constructor instead of reflection which is much faster public class CommentsDocument { @Id private CommentsKey key; @Field private List<String> comments; }
-
Register custom converters in Aerospike configuration:
AerospikeConfiguration.java@Configuration public class AerospikeConfiguration extends AbstractAerospikeDataConfiguration { // other code omitted @Override protected List<?> customConverters() { return List.of( CommentsKey.CommentsKeyToStringConverter.INSTANCE, CommentsKey.StringToCommentsKeyConverter.INSTANCE ); } }
-
Create repository that uses your custom key:
CommentsRepository.javaimport org.springframework.data.repository.CrudRepository; public interface CommentsRepository extends CrudRepository<CommentsDocument, CommentsKey> { }