【问题标题】:find record by Id and another Id in a list在列表中按 Id 和另一个 Id 查找记录
【发布时间】:2021-10-31 03:27:48
【问题描述】:

我有一个看起来像这样的CrudRepository

public interface MyDocumentRepository extends CrudRepository<MyDocument, String> {}

在我的对象 MyDocument 中,我有:

@DynamoDBTable(tableName = "MyDocument ")
public class MyDocument {

   @DynamoDBHashKey
   private String id;

   @DynamoDBAttribute
   private List<String> anotherIds;
   ...
}

我试图通过 id1 和 id2 获取所有可以包含 anotherId 的文档:

List<MyDocument> findAllByIdAndAnotherIdContains(String id, String anotherId);

但这对我不起作用,我收到此错误:

class java.lang.String cannot be cast to class java.util.List (java.lang.String and java.util.List are in module java.base of loader 'bootstrap')

我尝试了很多方法,但都返回此错误:

List<MyDocument> findAllByIdAndAnotherIdsContains(String id, List<String> anotherId);
List<MyDocument> findByIdAndAnotherIdsContains(String id, List<String> anotherId);
List<MyDocument> findByIdAndAnotherIdsContains(String id, String anotherId);
List<MyDocument> findByIdAndAnotherIdsContaining(String id, String anotherId);
List<MyDocument> findByIdAndAnotherIdsContaining(String id, List<String> anotherId);

知道如果没有@Query,我该怎么做吗?

【问题讨论】:

    标签: java spring-boot spring-data-jpa amazon-dynamodb crud-repository


    【解决方案1】:

    首先要做的事情。您的实体上有一个类型为List&lt;String&gt; 的字段。这不是您表上的原始列。它至少应该用@ElementCollection 注释。我还看到你想念@Id

    public class MyDocument {
       @Id
       private String id;
       @ElementCollection
       private List<String> anotherIds;
    }
    

    然后你可以再试一次

    List&lt;MyDocument&gt; findAllByIdAndAnotherIds(String id, String anotherId);

    【讨论】:

    • 感谢您的回答,事实上我使用的是 DynamoDBTable 我更改了我的问题以获得更多详细信息
    【解决方案2】:

    以下应该有效:

    List<MyDocument> findAllByIdAndAnotherIds(String id, List<String> anotherIds);
    

    Containing关键字用于检查字符串,在SQL中读作“LIKE %argument%”。

    【讨论】:

    • 谢谢你的回答,但我得到了同样的错误class java.lang.String cannot be cast to class java.util.List (java.lang.String and java.util.List are in module java.base of loader 'bootstrap')
    • 您能否尝试List&lt;MyDocument&gt; findAllByIdAndAnotherIds(String id, List&lt;String&gt; anotherIds);List&lt;MyDocument&gt; findAllByIdAndAnotherIdsIn(String id, List&lt;String&gt; anotherIds); 使用仅包含所需ID 的列表?
    • 谢谢List&lt;MyDocument&gt; findAllByIdAndAnotherIds(String id, List&lt;String&gt; anotherIds); 工作正常,但如果我通过AnotherIds 的所有元素,但就我而言,我想要任何一个
    • 不确定我是否理解您的评论。如果您创建一个只有一个“anotherId”作为findAllByIdAndAnotherIds 方法参数的列表,它不起作用吗? findAllByIdAndAnotherIdsIn 呢?
    猜你喜欢
    • 2012-08-16
    • 2018-07-27
    • 2023-03-25
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    相关资源
    最近更新 更多