Vaadin upload image and store it to database

I am using a Vaadin upload component and so far I have managed to upload an image to a directory, and display it in a panel component after it is successfull uploaded. What I want to do after this, is to insert it in the database aswell. What I have is a table called Show which has a name, date and an image. In the Show class I have tried to have my image as a byte array or as a Blob.

Column(name=“imagine”)
private byte imagine;

@Lob
@Column(name=“imagine”)
private Blob imagine;

In the upload succeded method I want to convert the file to a byte array, and so far I have tried this:

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(); }

I tried also this:
byte data = Files.readAllBytes(new File(“C:\Users\Cristina_PC\Desktop\” + event.getFilename()).toPath());
uIP.uploadImage(data);

uIP it is actually my uploadImagePresenter, where I tried to transform the byte array to Blob, or simply pass it to the repository as byte array

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

In my repository, in my updateAfterImage method I have:

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

Either with Blob or a byte array, I can’t manage to update the existing show by setting its image and update it in the database (the cell remains NULL). Also I get no error to help me figure out what is going wrong. Any help/advice would be useful. Thanks!

Did you tried to invoke persist or merge in updateAfterImage(…) after setting image data?

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

With both merge or persist, i get the following error:
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist

which makes sense because the object show has already an ID which is auto generated

Where does show instance come from?
If show is a new entity use em.persist(show) otherwise you can obtain a fresh instance with em.find(…), change it, and then em.merge(…)

HTH
Marco

Changed the method to:

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

Now it works and I can see the image was added to the database
Thank you very much for your help!