2

I have a CrudRepository that look like this:

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

In my object MyDocument I have:

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

   @DynamoDBHashKey
   private String id;

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

I tried to get all documents by id1 that equal to id and by id2 that can be contains anotherId:

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

But this not work with me and I get this error:

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')

I tried many ways but all them return this error:

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);

Any idea how can I do this without @Query please?

Doesn't Matter
  • 1,061
  • 3
  • 11
  • 29

2 Answers2

1

The following should work:

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

Containing keyword is used to check Strings and reads as "LIKE %argument%" in SQL.

João Dias
  • 16,277
  • 6
  • 33
  • 45
  • Thank you for your answer, bu I get the same error `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')` – Doesn't Matter Sep 01 '21 at 16:18
  • Can you please try `List findAllByIdAndAnotherIds(String id, List anotherIds);` or `List findAllByIdAndAnotherIdsIn(String id, List anotherIds);` with the list containing only the desired ID? – João Dias Sep 01 '21 at 17:31
  • thank you `List findAllByIdAndAnotherIds(String id, List anotherIds);` works fine, but If I pass all elements of `AnotherIds` but in my case I want any one – Doesn't Matter Sep 02 '21 at 08:02
  • Not sure if I understood your comment. Doesn't it work if you create a list with only one "anotherId" as a parameter of `findAllByIdAndAnotherIds` method? What about `findAllByIdAndAnotherIdsIn`? – João Dias Sep 02 '21 at 08:53
1

First things first. You have a field on your entity that is of type List<String>. This is not a primitive column on your table. It should at least be annotated with @ElementCollection. I also see you miss the @Id.

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

Then you can try again with

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

Panagiotis Bougioukos
  • 15,955
  • 2
  • 30
  • 47