The SQL database BLOB type is in Java represented as byte[]
. This is in JPA further to be annotated as @Lob
. So, your model basically need to look like this:
@Entity
public class SomeEntity {
@Lob
private byte[] image;
// ...
}
As to dealing with Part
, you thus basically need to read its InputStream
into a byte[]
. Apache Commons IO IOUtils
is helpful here:
InputStream input = uploadedFile.getInputStream();
byte[] image = IOUtils.toByteArray(input); // Apache commons IO.
someEntity.setImage(image);
// ...
Or if you prefer standard Java API which is only a bit more verbose:
InputStream input = uploadedFile.getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[10240];
for (int length = 0; (length = input.read(buffer)) > 0;) output.write(buffer, 0, length);
someEntity.setImage(output.toByteArray());
// ...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…