如何从春季将@Lob数据保存到Postgres数据库?

问题描述

我想使用Spring中的@Lob批注将编码后的图像保存到Postgres数据库中。测试应用程序,浏览图像然后保存时没有错误。但是,当我打开数据库而不是image列中的base64编码图像时,我只有几个数字(41417、41418等)。

这是我班上代码的一部分。

public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
private String name;

@Lob
private String imageBase64;

这是我用来将对象保存到数据库中的功能

public Product saveProduct(Product product,multipartfile image) throws IOException {
    if (image != null && !image.getName().isEmpty()) {
        byte[] bytes = image.getBytes();
        String base64Image = String.format("data:%s;base64,%s",image.getContentType(),Base64.getEncoder().encodetoString(bytes));
        product.setimageBase64(base64Image);
    }
    return this.productRepository.save(product);
}

但是当将其保存到数据库中时,它看起来像这样(列image_base64)。

enter image description here

解决方法

您的@Lob 正确保存正确。您看到的值(41417代表其OID。

要查看大对象的内容,可以使用Postgres的lo_get函数(假设您使用的是9.4+版本):

SELECT lo_get(cast(image_base64 as bigint)) FROM products WHERE id = 1;