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

时间:2017-05-22 12:31:26

标签: java mysql hibernate jsp servlets

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

        }
    }
}

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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

以上例子的解释:

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