如何使用 HIbernate 作为 BLOB 将此图像保存到 MySQL 数据库



如何使用Hibernate将此上传的图像保存到MySQL数据库? 我是否需要将此图像转换为字节数组,或者还有其他方法可以做到这一点吗?

try {
    // parses the request's content to extract file data
    List formItems = upload.parseRequest(request);
    Iterator iter = formItems.iterator();
    // iterates over form's fields
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        // processes only fields that are not form fields
        if (!item.isFormField()) {
            String fileName = new File(item.getName()).getName();
            String filePath = uploadPath + File.separator + fileName;
            File storeFile = new File(filePath);
            System.out.println("Image file name is :" + fileName);
            // saves the file on disk
            item.write(storeFile);
        }
    }
}

Java for MySQL 中 Blob 的等效映射类型是 byte[] 。您应该在 Hibernate 中使用相应的方言并注释属性,例如

@Lob
@Column(name = "data", columnDefinition = "blob", length = 16777215)
public byte[] getData() {
  return this.data;
}

这是一个演示示例,请仔细阅读并询问您是否有任何问题

https://github.com/loiane/hibernate-image-example

以上例子的解释:

https://dzone.com/articles/how-load-or-save-image-using

最新更新