Java 8 optional 无值存在

huangapple go评论69阅读模式
英文:

Java 8 optional No value present

问题

@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;
}
public interface ImageRepository extends JpaRepository<ImageModel, Long> {
    Optional<ImageModel> findByName(String name);
    Optional<ImageModel> findById(Long id);
}
@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;
    }
}
英文:

I have made this function and used optional although my image is not getting returned and is throwing an error NO VALUE PRESENT even though my db (MySQL) has data stored with the name

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

This is my dao class

public interface ImageRepository extends JpaRepository&lt;ImageModel, Long&gt; {
Optional&lt;ImageModel&gt; findByName(String name);
Optional&lt;ImageModel&gt; findById(Long id);
}

This is my model class where i have defined mysql database

@Entity
@Table(name = &quot;image_table&quot;)
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 = &quot;id&quot;)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = &quot;name&quot;)
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 = &quot;pic&quot;, length = 1000)
private byte[] pic;
@Column(name = &quot;type&quot;)
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;
}
}

答案1

得分: 1

"提示就在名字里。一个 Optional 对象指的是不一定必须存在的东西。如果 Optional 的实例不存在,你需要告诉应用程序该怎么做:

final Optional&lt;ImageModel&gt; retrievedImage = imageRepository.findByName(imageName);
return retrievedImage.get().orElse(null);

关于你的数据查询没有返回你所需的内容,我会说那是一个独立的问题,而你提供的代码并没有详细说明数据库查询的情况。"

英文:

The hint is in the name. An Optional object refers to something that doesn't necessarily have to be there. You need to tell the app what to do if an instance of Optional is not present:

final Optional&lt;ImageModel&gt; retrievedImage = imageRepository.findByName(imageName);
return retrievedImage.get().orElse(null);

WRT your data query not returning what you're looking for, I would say that is a separate issue, and the code you have given doesn't detail that query of the database.

答案2

得分: 0

可选模式(也称为单子模式)允许您控制数据是否存在的流程,从而帮助您避免空指针异常(即“十亿美元的错误”)。

您可以通过以下方式利用可选模式:

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

  2. 如果需要,可以使用 optional.orElseGet 返回一个新的图像。

  3. 例如,如果要在数据库中没有图像时抛出异常并以这种方式停止流程,可以使用 optional.orElseThrow(...)

  4. 在if条件中使用 optional.isPresent() 来处理图像为空的情况,从而更精确地控制流程。

英文:

The optional pattern ( also monad) lets you control the flow if data is present or not, which helps you avoid null pointer exceptions ( the billion dollar mistake)

You can take advandage of the optional pattern by either using:

  1. optional.ifPresent(e-&gt; decompress(e))

  2. optional.orElseGet( return a new Image) if this is the use case.

  3. optional.orElseThrow(...) for example if you want to throw an exception if there's no
    image present in the database and stop the flow in this way.

  4. use optional.isPresent() in an if condition to hanadle the the case in which the image is null.

And control your flow more precisely and

huangapple
  • 本文由 发表于 2020年8月11日 22:13:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/63360017.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定