Spring Data DynamoDB无需@Query实现按ID与列表字段包含值查询
错误原因
你遇到的类型转换报错,是因为Spring Data DynamoDB的Contains/Containing衍生查询关键字默认是为String类型的模糊匹配设计的,处理List类型属性时会尝试将属性值转为String做匹配,自然会触发String和List的类型转换异常。而且目前Spring Data DynamoDB对集合类型的包含查询衍生关键字支持度很低,不建议硬凑方法名实现需求。
不用@Query的解决方案
方案1:结合哈希键特性手动过滤(最简实现)
你的id字段是DynamoDB的哈希主键,单哈希键查询的结果最多只有1条记录,完全可以先按id查出记录,再手动判断anotherIds是否包含指定值即可,不需要额外复杂逻辑:
public interface MyDocumentRepository extends CrudRepository<MyDocument, String> { // 新增默认方法实现逻辑 default Optional<MyDocument> findByIdAndContainAnotherId(String id, String anotherId) { return findById(id) .filter(doc -> doc.getAnotherIds() != null && doc.getAnotherIds().contains(anotherId)); } }
方案2:用DynamoDBTemplate构造查询(适合复杂场景)
如果后续需要扩展非主键查询条件,可以自定义Repository实现类,用DynamoDBTemplate构造原生查询条件:
- 首先定义自定义查询接口
public interface CustomMyDocumentRepository { List<MyDocument> findByIdAndAnotherIdsContains(String id, String anotherId); }
- 实现自定义接口
@Repository public class CustomMyDocumentRepositoryImpl implements CustomMyDocumentRepository { private final DynamoDBTemplate dynamoDBTemplate; public CustomMyDocumentRepositoryImpl(DynamoDBTemplate dynamoDBTemplate) { this.dynamoDBTemplate = dynamoDBTemplate; } @Override public List<MyDocument> findByIdAndAnotherIdsContains(String id, String anotherId) { DynamoDBQueryExpression<MyDocument> queryExpression = new DynamoDBQueryExpression<MyDocument>() .withHashKeyValues(new MyDocument(id)) .withFilterExpression("contains(anotherIds, :anotherId)") .withExpressionAttributeValues(Map.of(":anotherId", new AttributeValue(anotherId))); return dynamoDBTemplate.query(MyDocument.class, queryExpression); } }
- 让原有Repository继承自定义接口即可使用
public interface MyDocumentRepository extends CrudRepository<MyDocument, String>, CustomMyDocumentRepository {}
内容的提问来源于stack exchange,提问作者Youcef LAIDANI
相关产品推荐
相关产品推荐

