Hibernate中Blob对象类型的使用

               

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

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

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

<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC        "-//Hibernate/Hibernate Configuration DTD//EN"        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration>    <session-factory>        <property name="connection.username">root</property>        <property name="connection.password"></property>        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>        <!-- 下面的 hibernate 指的是 数据库名,即所用的数据库 -->        <property name="connection.url">jdbc:mysql:///hibernate?useUnicode=true&characterEncoding=UTF-8</property>        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>        <property name="show_sql">true</property>        <property name="format_sql">true</property>        <!--<property name="hbm2ddl.auto">create</property>-->        <property name="hbm2ddl.auto">update</property>        <!-- getCurrentSession方式获取 session 时需要添加如下配置 -->        <property name="hibernate.current_session_context_class">thread</property>        <mapping resource="Students.hbm.xml"/>        <!-- DB schema will be updated if needed -->        <!-- <property name="hbm2ddl.auto">update</property> -->    </session-factory></hibernate-configuration>


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映射到数据库中所使用的类型)
<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping>    <class name="Students" table="students">        <id name="sid" type="int">            <column name="sid"/>            <!--<generator class="assigned"/>-->            <generator class="native"/>        </id>        <property name="sname" type="java.lang.String">            <column name="sname"/>        </property>        <property name="gender" type="java.lang.String">            <column name="gender"/>        </property>        <!--使用 java.util.Date 类型,在数据库中字段的类型为 datetime(会出现时分秒)-->        <!--<property name="birthday" type="java.util.Date">-->        <!--使用 Hibernate 中的数据类型 date,在数据库中字段的类型为 date (就不会出现时分秒了)-->        <property name="birthday" type="date">            <column name="birthday"/>        </property>        <property name="address" type="java.lang.String">            <column name="address"/>        </property>        <property name="picture" type="java.sql.Blob">            <column name="picture"/>        </property>    </class></hibernate-mapping>


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 测试方法:

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

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

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

 



           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/qq_43685640/article/details/86431251
今日推荐