Home > database >  JPA query of list of Strings fails
JPA query of list of Strings fails

Time:12-20

I have a JPA-enabled, mongoDB-backed Spring Boot REST service in which I'm having trouble querying a list in the entity. They look like this:

{
  "_id": {
    "$oid": "639df2e83f61353766023bf9"
  },
  "body": "body1",
  "name": "name1",
  "tags": [
    "tag1"
  ],
  "_class": "ca.footeware.rest.recipes.model.Recipe"
}

Note that "tags" is an array of Strings.

My repository extends MongoRepository<Recipe, String>. I have two methods, the first works but the second doesn't:

Page<Recipe> findByNameOrBodyContainingIgnoreCaseOrderByNameAsc(String name, String body, Pageable pageable);

Page<Recipe> findByNameOrBodyOrTagsContainingIgnoreCaseOrderByNameAsc(String name, String body, String tags, Pageable pageable);

The addition of "OrTags" and the accompanying "tags" parameter causes a search for "tag" to fail. Further it seems everything after "OrTags" is ignored, i.e. the "Containing", "IgnoreCase" and "OrderBy" are lost.

What am I doing wrong?


OK, for those playing along at home, I made some changes I hesitate to call progress. I saw somewhere that the problem might be the type of the list, i.e. String. So I created a record:

public record Tag(String value) {
  public Tag(String value) {
    this.value = value;
  }
}

And changed my entity class to:

public class Recipe {
  private String body;n
  @Id
  private String id;
  private List<String> images;
  private String name;
  private List<Tag> tags;
  ...

In mongodb's Compass app it shows its JSON as:

{
  "_id": {
    "$oid": "639e3f4b0f60a06354564152"
  },
  "body": "body1",
  "name": "name1",
  "tags": [
    {
      "value": "tag1"
    }
  ],
  "_class": "ca.footeware.rest.recipes.model.Recipe"
}

My repository method is now:

Page<Recipe> findByNameOrBodyOrTagsValueContainingIgnoreCaseOrderByNameAsc(String name, String body, String tags, Pageable pageable);

And it works! Well kinda...if I search for the fields' exact value it works. The ContainingIgnoreCaseOrderByNameAsc is being ignored. Not good in a search function.

Anyone have any ideas? Any help would be greatly appreciated. Oh I should've mentioned I'm on Spring Boot 3 and Java 19 if that matters.

CodePudding user response:

The correct sequence of elements in the repository method is:

findByNameContainingIgnoreCaseOrBodyContainingIgnoreCaseOrTagsValueContainingIgnoreCaseOrderByNameAsc

Not sure if my modification from List of String to List of Tag made any difference.

  • Related