Am1rr3zA
Am1rr3zA

Reputation: 7421

Store and retrieve Image by Hibernate

I want to know what is the best way to store an image with help of hibernate (into MySQL) I have this class Mapping

@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;

Also, I have PictureDAO; I want to know how should I implement My PictureDAO to save and retrieve Image.

Upvotes: 4

Views: 9483

Answers (1)

Maurice Perry
Maurice Perry

Reputation: 32831

The version with the byte array is simple.

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();
    }
}

Upvotes: 5

Related Questions