【hibernate】存储图片

【hibernate】存储图片

转载:

package cn.ycx.study.hibernate.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
@Entity
@org.hibernate.annotations.DynamicInsert
@org.hibernate.annotations.DynamicUpdate
public class User {
    @Id
    @GeneratedValue(generator="id_generator")
    protected long id;
    protected String username;
    @Lob
    protected byte[] photo; // 数组类型
    @Lob
    protected java.sql.Blob image; // 大数据类型
    
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public byte[] getPhoto() {
        return photo;
    }
    public void setPhoto(byte[] photo) {
        this.photo = photo;
    }
    public java.sql.Blob getImage() {
        return image;
    }
    public void setImage(java.sql.Blob image) {
        this.image = image;
    }
}

测试

    @Test
    public void testInsert() {
        User u = new User();
        u.setUsername("admin");
        try {
            FileInputStream p = new FileInputStream(new File("E:/wx/image.jpg"));
            int len = Long.valueOf(p.available()).intValue();
            byte[] photo = new byte[len];
            p.read(photo, 0, len);
            u.setPhoto(photo);
            p.close();
            java.sql.Blob blog = this.session.getLobHelper().createBlob(photo);
            u.setImage(blog);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        this.session.persist(u);
        assertTrue( true );
    }
原文地址:https://www.cnblogs.com/yangchongxing/p/10396287.html