我只是想简单地问一下当Spring Boot Web应用程序的JPA在数据库中保存数据或BLOB(使用@LOB)或字节数组数据时,在数据库中保存图像的真正形式是什么。 是将整个字节数据保存在数据库中还是 它将只保存该字节数组对象的引用或地址,实际上将其保存到系统的文件空间中。
我想专门询问 Spring Boot JPA Repository。 请解释一下。 如果有任何演示示例进行测试,请提供
最佳答案
转到此 repository并转到 display-image-from-db
分支。基本方法如下:
在您拥有的实体中:
@Lob private Byte[] image;
获取图像ImageController.java
- 您通过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"; }
调用
imageService
将传递给file
的图像作为参数保存。该服务基本上将图像内容复制到一个字节数组,最后您将这个字节数组分配给您的实体。
@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(); } }
要获得完整的源代码,请访问存储库,这绝对有帮助。 但是我强烈建议将文件存储在磁盘上而不是数据库中。数据库应该只存储文件的路径。对于这样的解决方案,这里有一个例子:link
关于java - Spring Boot JPA(Hibernate)如何保存Images,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50363639/