I just want to simply ask when Spring Boot Web Application's JPA saves Data or BLOB(using @LOB) or byte array data in the Database what is the real form of Saving The Images in Database. is it going to save the Whole byte data in Database or it is going to save only the reference or Address for that byte Array Object and in reality saving it into the System's file Space.
I want to ask Specifically for Spring Boot JPA Repository. Please explain it. and if any demo example to Test it out please provide it
Go to this repository and go to the display-image-from-db
branch. The basic approach is the following:
In the entity you have:
@Lob
private Byte[] image;
ImageController.java
- you get the image via a MultipartFile
@PostMapping("recipe/{id}/image")
public String handleImagePost(@PathVariable String id, @RequestParam("imagefile") MultipartFile file){
imageService.saveImageFile(Long.valueOf(id), file);
return "redirect:/recipe/" + id + "/show";
}
Call the imageService
to save the image passing the file
as an argument.
The service basically copies the image content to a byte array, and finally you assign this byte array to your entity.
@Override
@Transactional
public void saveImageFile(Long recipeId, MultipartFile file) {
try {
Recipe recipe = recipeRepository.findById(recipeId).get();
Byte[] byteObjects = new Byte[file.getBytes().length];
int i = 0;
for (byte b : file.getBytes()){
byteObjects[i++] = b;
}
recipe.setImage(byteObjects);
recipeRepository.save(recipe);
} catch (IOException e) {
//todo handle better
log.error("Error occurred", e);
e.printStackTrace();
}
}
For the full source code go to the repo, that will definitely help. However I strongly suggest storing the files on the disk and not in the DB. The DB should only store the path to the files. For such solution here is an example: link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With