JPA Repository findAll with optional fields
Asked Answered
S

2

4

I have a controller try to search with optional field. The JPA entity class is defined as:

package demo;

import javax.persistence.*;

@Entity
public class UploadFile {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int id;
  private String name;

  public UploadFile() {
  }

  public UploadFile(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  @Override
  public String toString() {
    return "UploadFile{" +
        "id=" + id +
        ", name='" + name + '\'' +
        '}';
  }

}

The controller is defined in the following code:

@RequestMapping(value = "/searchFile", method = RequestMethod.GET)
public @ResponseBody
List<UploadFile> searchFile(@RequestParam("id") Optional<Integer> id, @RequestParam("name") Optional<String> name) {
    UploadFile newFile = new UploadFile();
    if (id.isPresent()) {
        newFile.setId(id.get());
    }
    if (name.isPresent()) {
        newFile.setName(name.get());
    }
    System.out.println("new File: " + newFile);

    //uploadFileRepository is a JpaRepository Class
    return List<UploadFile> files = uploadFileRepository.findAll(Example.of(newFile));
}

The database has one record:

ID      NAME    SIZE    TYPE  
1       index   111     html

When '/searchFile?id=1' hits server, the console prints:

new File: UploadFile{id=1, name='null'}

The http returns an empty array:

I want the /searchFile?id=1 to return the record with id 1, and also /searchFile?name=index to return the record with id 1 too.

Is there anything I did wrong?

Thanks!

Sunbow answered 2/3, 2019 at 4:56 Comment(2)
Your code looks good, the problem must be somewhere else. include the UploadFile class to your question.Balefire
@sh977218, can you add generated query?Giaimo
B
4

I think you cannot use the example to find records by id. (Which is quite logical, if you know the id then why do you need this feature at all?)

So if the id parameter is provided in the request then use findById(id) directly, otherwise fill all the provided properties of an example object and use the findAll(Example.of(example)) method.

Balefire answered 3/3, 2019 at 9:59 Comment(1)
Thanks! That's exactly what happened. I removed the ID and it worked.Sunbow
G
0

I think, its because of this,

if (name.isPresent()) {
        newFile.setSize(name.get()); 
}

You are doing newFile.**setSize**(name.get()); but it should(i believe) be newFile.set**Name**(name.get());

Giaimo answered 2/3, 2019 at 6:40 Comment(3)
The name parameter is null, so it doesn't matterBalefire
Hi, I've added the entity class, and correct the code, it still doesn't find the record.Sunbow
Can you add generated query for '/searchFile?id=1'?Giaimo

© 2022 - 2024 — McMap. All rights reserved.