find record by Id and another Id in a list

Viewed 111

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?

2 Answers

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.

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

Related