【问题标题】:JPA Repository findAll with optional fields带有可选字段的 JPA 存储库 findAll
【发布时间】:2019-07-24 02:53:45
【问题描述】:

我有一个控制器尝试使用可选字段进行搜索。 JPA实体类定义为:

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 + '\'' +
        '}';
  }

}

控制器在以下代码中定义:

@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' 访问服务器时,控制台会打印:

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

http 返回一个空数组:

我希望/searchFile?id=1 返回 id 为 1 的记录, 还有/searchFile?name=index 也可以返回 id 为 1 的记录。

是不是我做错了什么?

谢谢!

【问题讨论】:

  • 您的代码看起来不错,问题一定出在其他地方。在您的问题中包含 UploadFile 类。
  • @sh977218,你能添加生成的查询吗?

标签: java spring spring-data-jpa


【解决方案1】:

我认为您不能使用 example 按 id 查找记录。 (这很合乎逻辑,如果你知道 id 那你为什么需要这个功能呢?)

所以如果请求中提供了id参数则直接使用findById(id)否则填充示例对象的所有提供属性并使用findAll(Example.of(example))方法。

【讨论】:

  • 谢谢!这正是发生的事情。我删除了 ID,它起作用了。
【解决方案2】:

我想,是因为这个,

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

你正在做newFile.**setSize**(name.get());,但它应该(我相信)是newFile.set**Name**(name.get());

【讨论】:

  • name参数为null,所以没关系
  • 您好,我已经添加了实体类,并且更正了代码,仍然没有找到记录。
  • 您可以为“/searchFile?id=1”添加生成的查询吗?
猜你喜欢
  • 2018-06-15
  • 2018-01-02
  • 2016-05-21
  • 2020-11-27
  • 2016-03-26
  • 2021-07-12
  • 1970-01-01
  • 2021-09-03
  • 1970-01-01
相关资源
最近更新 更多