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

flvtvl50  于 2023-05-18  发布在  Mysql
关注(0)|答案(2)|浏览(217)

如何使用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);

        }
    }
}
jfgube3f

jfgube3f1#

在Java for MySQL中,Blob的等效Map类型是byte[]。您应该在Hibernate中使用相应的方言,并对属性进行如下注解

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

0s7z1bwu2#

这是一个演示的例子,请通过它,并询问是否有任何问题u
https://github.com/loiane/hibernate-image-example
以上示例说明:
https://dzone.com/articles/how-load-or-save-image-using

相关问题