首页 > 解决方案 > 无法将图像添加到 postgresql

问题描述

我正在 Spring Boot 上创建商店,我需要为我的产品提供图像。我有一张桌子

create table if not exists products
(
    id     bigint unique primary key not null,
    name   varchar(50)               not null unique,
    price  varchar(50)               not null,
    serial varchar(50)               not null unique,
    picture bytea
);

我有简单的产品实体类,还有带有基本 CRUD 方法的存储库和服务。我的所有产品都在主类的程序启动时插入到表中

@Bean
CommandLineRunner runner(ProductService productService, UserService userService) {
    return args -> {
        productService.saveProduct(new Products(11L, "black mask", 100, 11111, "img/mask_black.png")); //and so on

我的图像保存在资源/静态/img/ 中,但它不起作用。我在相关主题中阅读了很多答案,但这没有帮助。我应该怎么办?

标签: javaspringimage

解决方案


是的,你可以添加它,但我建议你创建一个新的表格图像并分开保存图像和数据,尽管在任何选择上你都会检索很多不必要的数据

create table if not exists products
(
    id        bigint unique primary key not null,
    name      varchar(50)               not null unique,
    price     varchar(50)               not null,
    serial    varchar(50)               not null unique,
    pictureId bigint                    not null
);

create table if not exists productPictures
(
    id      bigint unique primary key not null,
    picture bytea                     not null
);

并在它们之间施加一些约束。

顺便看看https://www.postgresql.org/docs/9.1/datatype-binary.html的 postgres 文档


推荐阅读