英文:
How to save @Lob data from spring in to a Postgres database?
问题
我想使用Spring中的@Lob注解将编码图像保存到Postgres数据库中。在测试应用程序时没有出现错误,我浏览了一张图片然后保存它。但是当我打开数据库时,图像列中没有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列)。
英文:
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).
答案1
得分: 4
你的 @Lob
标记确实保存正确。你看到的值(41417
)代表它的 OID。
要查看大对象的内容,你可以使用 PostgreSQL 的 lo_get
函数(假设你使用的是 9.4 版本或更高版本):
SELECT lo_get(cast(image_base64 as bigint)) FROM products WHERE id = 1;
英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论