Spring Boot JPA(Hibernate)如何保存图像 [英] How Spring Boot JPA(Hibernate) saves Images

查看:169
本文介绍了Spring Boot JPA(Hibernate)如何保存图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我想特别问一下Spring Boot JPA存储库. 请解释一下. 如果有演示示例进行测试,请提供

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-您通过MultipartFile

  • 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";
    }
    

  • 调用imageService来保存通过file作为参数的图像.

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

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

    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

    这篇关于Spring Boot JPA(Hibernate)如何保存图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆