簡體   English   中英

Java 8 可選 不存在值

[英]Java 8 optional No value present

我已經制作了這個 function 並使用了可選的,盡管我的圖像沒有被返回並且拋出錯誤 NO VALUE PRESENT 即使我的數據庫(MySQL)存儲了帶有名稱的數據

@GetMapping(path = { "/get/{imageName}" })
public ImageModel getImage(@PathVariable("imageName") String imageName) throws IOException {
    final Optional<ImageModel> retrievedImage = imageRepository.findByName(imageName);
    ImageModel img = new ImageModel(retrievedImage.get().getName(), retrievedImage.get().getType(),
    decompressBytes(retrievedImage.get().getPic()));
    return img;
}

這是我的刀 class

public interface ImageRepository extends JpaRepository<ImageModel, Long> {
    Optional<ImageModel> findByName(String name);
    Optional<ImageModel> findById(Long id);
}

這是我的 model class 我在其中定義了 mysql 數據庫

@Entity
@Table(name = "image_table")
public class ImageModel {
    public ImageModel() {
        super();
    }
    public ImageModel(String name, String type, byte[] pic) {
        this.name = name;
        this.type = type;
        this.pic = pic;
    }
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "name")
    private String name;
    //image bytes can have large lengths so we specify a value
    //which is more than the default length for picByte column
    @Column(name = "pic", length = 1000)
    private byte[] pic;
    @Column(name = "type")
    private String type;

    public String getName() {
        return name;
    }

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

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public byte[] getPic() {
        return pic;
    }

    public void setPic(byte[] pic) {
        this.pic = pic;
    }
}

提示在名稱中。 Optional的 object 指的是不一定必須存在的東西。 如果Optional的實例不存在,您需要告訴應用程序該怎么做:

final Optional<ImageModel> retrievedImage = imageRepository.findByName(imageName);
return retrievedImage.get().orElse(null);

WRT 您的數據查詢沒有返回您要查找的內容,我會說這是一個單獨的問題,並且您提供的代碼沒有詳細說明數據庫的查詢。

可選模式(也是 monad)讓您可以控制數據是否存在,這可以幫助您避免 null 指針異常(十億美元的錯誤)

您可以通過以下方式利用可選模式:

  1. optional.ifPresent(e-> decompress(e))

  2. optional.orElseGet (返回一個新圖像)如果這是用例。

  3. optional.orElseThrow(...)例如,如果您想在數據庫中不存在圖像時拋出異常並以這種方式停止流程。

  4. 在 if 條件中使用optional.isPresent()來處理圖像為 null 的情況。

更精確地控制您的流量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM