JPA Repository findAll 带有可选字段
我有一个控制器尝试使用可选字段进行搜索.JPA实体类定义为:
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));
}
数据库有一条记录:
ID NAME SIZE TYPE
1 index 111 html
当'/searchFile?id=1'命中服务器时,控制台打印:
When '/searchFile?id=1' hits server, the console prints:
new File: UploadFile{id=1, name='null'}
http 返回一个空数组:
The http returns an empty array:
我希望 /searchFile?id=1
返回 ID 为 1 的记录,以及 /searchFile?name=index
也返回 ID 为 1 的记录.
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.
我做错了什么吗?
谢谢!
我认为您不能使用 example
通过 id 查找记录.(这是非常合乎逻辑的,如果您知道 id,那么您为什么完全需要此功能?)
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?)
因此,如果请求中提供了 id 参数,则直接使用 findById(id)
,否则 填充示例对象的所有提供的属性并使用 findAll(Example.of(example))
方法.
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.