Vaadin上传图片并将其存储到数据库

Vaadin upload image and store it to database

我使用的是Vaadin 上传组件,到目前为止我已经设法将图片上传到目录,并在上传成功后将其显示在面板组件中。在此之后我想做的是将它也插入到数据库中。我有一个名为 Show 的 table,它有名称、日期和图像。在 Show class 中,我尝试将图像作为字节数组或 Blob。

Column(name="image")
private byte[] image;

@Lob
@Column(name="image")
private Blob image;

在上传成功的方法中,我想将文件转换为字节数组,到目前为止我已经试过了:

File file = new File("C:\Users\Cristina_PC\Desktop\" + event.getFilename());
byte[] bFile = new byte[(int) file.length()];
try {
    FileInputStream fileInputStream = new FileInputStream(file);
    fileInputStream.read(bFile);
    uIP.uploadImage(bFile);
    fileInputStream.close();
} catch (Exception e) {
    e.printStackTrace();
}

我也试过这个:

byte[] data = Files.readAllBytes(new File("C:\Users\Cristina_PC\Desktop\" + event.getFilename()).toPath());
uIP.uploadImage(data);

uIP 它实际上是我的 uploadImagePresenter,我在这里尝试将字节数组转换为 Blob,或者只是将它作为字节数组传递给存储库

 public void uploadImage(byte[] data) throws SerialException, SQLException{
    //Blob blob = new javax.sql.rowset.serial.SerialBlob(data);
    showRepo.updateAfterImage(show, data);         // or (show, blob)
}

在我的存储库中,在我的 updateAfterImage 方法中我有:

public void updateAfterImage(Show show, byte[] data)             //or Blob data
{
     em.getTransaction().begin();                       //em - EntityManager
     show.setImage(data);
     em.getTransaction().commit();
}

无论是使用 Blob 还是字节数组,我都无法通过设置其图像来更新现有节目并在数据库中更新它(单元格保持为 NULL)。我也没有错误来帮助我找出问题所在。任何 help/advice 都会有用。谢谢!

我找到了解决办法。使它起作用的是:

em.getTransaction().begin(); 
em.find(Show.class, show.getId()); 
show.setImage(data); 
em.merge(spectacol); 
em.getTransaction().commit();

在显示存储库中我的 updateAfterImage 方法中。