How to save @Lob data from spring in to a Postgres database?

Viewed 947

I want to save an encoded image in to a Postgres database using the @Lob annotation in Spring. There are no errors when I test the application, I browse an image and then save it. But when I open the database instead of the base64 encoded image in the image column I just have a couple of numbers (41417, 41418 and so on).

Here is a part of the code from my class.

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

@NotNull
private String name;

@Lob
private String imageBase64;

Here is the function I use to save the object in to the database.

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

But when it saves it in to the database it looks like this (column image_base64).

enter image description here

1 Answers

Your @Lob did save correctly. The value that you see (41417) represents its OID.

To see the contents of the large object, you can use Postgres' lo_get function (assuming you're using version 9.4+):

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