Spring Boot JPA(Hibernate) 如何保存图像

Man*_*rma 3 java spring hibernate jpa spring-boot

我只想简单地问一下Spring Boot Web Application的JPA何时在数据库中保存数据或BLOB(使用@LOB)或字节数组数据时,在数据库中保存图像的真实形式是什么。它是将整个字节数据保存在数据库中,还是只保存该字节数组对象的引用或地址,实际上将其保存到系统的文件空间中。

我想专门询问 Spring Boot JPA 存储库。请解释一下。如果有任何演示示例来测试它,请提供它

Ph0*_*n1x 10

转到此存储库并转到display-image-from-db分支。基本方法如下:

  • 在实体中,您拥有:

    @Lob
    private Byte[] image;
    
    Run Code Online (Sandbox Code Playgroud)
  • ImageController.java - 你通过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";
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 调用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();
    }
    }
    
    Run Code Online (Sandbox Code Playgroud)

对于完整的源代码,请访问 repo,这肯定会有所帮助。但是我强烈建议将文件存储在磁盘上而不是数据库中。DB 应该只存储文件的路径。对于这样的解决方案,这里有一个例子:链接


小智 1

它将保存数据库中的所有字节,不会将其导出到文件系统并保存目录。您必须在代码中专门执行该部分。