java - 通过 Hibernate 存储和检索图像

标签 java hibernate blob image

我想知道在 hibernate 的帮助下存储图像的最佳方式是什么(进入 MySQL) 我有这个类映射

@Entity
@Table(name = "picture")
public class PictureEntity implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue
    private int id;
    @Column(name = "format", length = 8)
    private String format;
    //@Basic(fetch = FetchType.LAZY)
    @Lob
    @Column(name = "context", nullable = true, columnDefinition = "mediumblob")
    private java.sql.Blob myBlobAttribute; // or byte[] no diff
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "branch_fk", referencedColumnName = "id", nullable = false)
    private BranchEntity branch;

此外,我还有 PictureDAO;我想知道我应该如何实现 My PictureDAO 来保存和检索图像。

最佳答案

字节数组的版本很简单。

public class PictureEntity implements Serializable {
    private byte[] imageBytes;

    public BufferedImage getImage() {
        InputStream in = new ByteArrayInputStream(imageBytes);
        return ImageIO.read(in);
    }

    public void setImage(BufferedImage image) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(image, "PNG" /* for instance */, out);
        imageBytes = out.toByteArray();
    }
}

关于java - 通过 Hibernate 存储和检索图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1177702/

相关文章:

java - 如何使用jSTL获取jsp中日历类型方法中设置的日期?

Java SWT - 将数据从组件返回到其他线程的最佳方式

java - 当 DB 有这样的约束时,为什么要使用 JPA/Hibernate 约束注释

java - Hibernate 单向关联问题

java - 使用 JDBC 创建数据库模式的模式

java - 即使使用 addNmeaListener 调用 OnNmeaMessageListener 也无法工作

java - hibernate/webapp 上下文中的对象相等性

javascript - 如何为所有用户提供 blob 和良好的文件名?

Azure Cloud Block Blob,防止进程覆盖其他进程所做的更改

google-apps-script - Google Apps 脚本中 Utilities.unzip(blob) 的 blob 是否有大小限制?