Hibernate中Blob对象类型的使用

       使用Intellij IDEA创建Hibernate项目,目录结构如下:

Hibernate中Blob对象类型的使用_第1张图片

       其中 assets/app.png 为将要存储的照片,src/hibernate.cfg.xml 为Hibernate的配置文件,Students为实体,Students.hbm.xml 为对象关系映射的配置文件,test目录下其中使用到的测试类为 StudentsTest 类,使用到junit进行测试。(其他两个与此次说明无关)

hibernate.cfg.xml(使用mysql数据库中名为 hibernate的数据库)




    
        root
        
        com.mysql.jdbc.Driver
        
        jdbc:mysql:///hibernate?useUnicode=true&characterEncoding=UTF-8
        org.hibernate.dialect.MySQLDialect

        true
        true
        
        update


        
        thread

        
        
        
    


Students.java (使用picture属性存储Blob类型数据)

import java.sql.Blob;
import java.util.Date;

/**
 * Created by DreamBoy on 2016/5/15.
 */
//学生类
public class Students {
    //1. 必须为公有的类
    //2. 必须提供公有的不带参数的默认的构造方法
    //3. 属性私有
    //4. 属性setter/getter封装

    private int sid; //学号
    private String sname; //姓名
    private String gender; //性别
    private Date birthday; //出生日期
    private String address; //地址
    private Blob picture; //照片

    public Students() {
    }

    public Students(int sid, String sname, String gender, Date birthday, String address) {
        this.sid = sid;
        this.sname = sname;
        this.gender = gender;
        this.birthday = birthday;
        this.address = address;
    }

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Blob getPicture() {
        return picture;
    }

    public void setPicture(Blob picture) {
        this.picture = picture;
    }

    @Override
    public String toString() {
        return "Students{" +
                "sid=" + sid +
                ", sname='" + sname + '\'' +
                ", gender='" + gender + '\'' +
                ", birthday=" + birthday +
                ", address='" + address + '\'' +
                '}';
    }
}

Students.hbm.xml(注意使用Hibernate映射到数据库中所使用的类型)




    
        
            
            
            
        
        
            
        
        
            
        

        
        
        
        
            
        
        
            
        

        
            
        
    


StudentsTest.java 测试类

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.*;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.Date;

/**
 * Created by DreamBoy on 2016/5/15.
 */
//测试类
public class StudentsTest {
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;

    @Before
    public void init() {
        //创建配置对象
        Configuration config = new Configuration().configure();
        //创建服务注册对象
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //创建会话工厂对象
        sessionFactory = config.buildSessionFactory(serviceRegistry);
        //会话对象
        session = sessionFactory.openSession();
        //开启事务
        transaction = session.beginTransaction();
    }

    @After
    public void destory() {
        transaction.commit(); //提交事务
        session.close(); //关闭会话
        sessionFactory.close(); //关闭会话工厂
    }

    @Test
    public void testSaveStudents() {
        //生成学生对象
        //Students s = new Students(1, "张三丰", "男", new Date(), "武当山");
        Students s1 = new Students();
        //如果 Students.hbm.xml 映射配置文件设置了 主键native,mysql中主键自增长,即便你设置了主键的值,也是不起作用的
        s1.setSname("s1");
        s1.setGender("男");
        s1.setBirthday(new Date());
        s1.setAddress("汕头");

        Students s2 = new Students();
        s2.setSname("s2");
        s2.setGender("女");
        s2.setBirthday(new Date());
        s2.setAddress("广州");

        //session.save(s); //保存对象进入数据库
        session.save(s1);
        session.save(s2);
    }

    @Test
    public void testWriteBlob() throws IOException {
        Students s = new Students(1, "张三丰", "男", new Date(), "武当山");
        //先获得照片文件
        //File f = new File("d:" + File.separator + "boy.jpg");

        /*File directory = new File("");//参数为空
        String courseFile = directory.getCanonicalPath() ;
        System.out.println(courseFile);*/

        File f = new File("assets/app.png");
        //获得文件输入流
        InputStream input = new FileInputStream(f);
        //创建一个Blob对象
        Blob image = Hibernate.getLobCreator(session).createBlob(input, input.available());
        //设置照片属性
        s.setPicture(image);
        input.close();
        session.save(s);
    }

    @Test
    public void testReadBlob() throws SQLException, IOException {
        Students s = (Students) session.get(Students.class, 1); //主键为1的Studetns记录
        //获得Blob对象
        Blob image = s.getPicture();
        //获得照片输入流
        InputStream input = image.getBinaryStream();
        //创建输出流
        File f = new File("assets/dest.png");
        OutputStream output = new FileOutputStream(f);
        //创建缓冲区
        byte[] buff = new byte[input.available()];
        input.read(buff);
        output.write(buff);
        input.close();
        output.close();
    }
}


       主要测试方法有两个 testWriteBlob 和 testReadBlob,保存一条含blob类型的记录和读取一条记录中的picture字段的值,并存储为图片文件。

运行 testWriteBlob 测试方法:

Hibernate中Blob对象类型的使用_第2张图片

Hibernate中Blob对象类型的使用_第3张图片

       查看数据库(插入成功):

Hibernate中Blob对象类型的使用_第4张图片

       运行testReadBlob方法,读取 刚插入的记录 的picture字段的值,并保存成图片:

Hibernate中Blob对象类型的使用_第5张图片

Hibernate中Blob对象类型的使用_第6张图片

       我们可以看到,成功读取并生成了一张图片:

 Hibernate中Blob对象类型的使用_第7张图片



你可能感兴趣的:(JavaEE)