Hibernate中Blob对象类型的使用

2023-05-16

       使用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字段的值,并保存成图片:

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

 



本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Hibernate中Blob对象类型的使用 的相关文章

  • PHP实现页面静态化——全部纯静态化

    先来看看php在服务器的执行过程 xff1a 当用户请求服务器php文件的时候 xff0c 服务器将对php文件进行语法分析 xff0c 其次是解析 xff0c 最后才运行 当php文件有内容输出时 xff0c 该内容会先经过服务器的php
  • PHP实现页面静态化——局部动态化

    上回说到 xff1a PHP实现页面静态化 全部纯静态化 这次实现PHP的局部动态化 xff0c 也就是说静态化的页面存在 动态 过程 xff0c 结合全部静态化技术 43 Ajax技术实现局部动态化 xff0c 局部更新页面 在上文的数据
  • CSS3的过渡 transition

    这里只考虑 chrome 的兼容 transition html lt DOCTYPE html gt lt html lang 61 34 en 34 gt lt head gt lt meta charset 61 34 UTF 8 3
  • CSS3中的3D旋转 rotate、3D位移 translate

    这里只考虑 chrome 的兼容 3DrotateDemo html lt DOCTYPE html gt lt html lang 61 34 en 34 gt lt head gt lt meta charset 61 34 UTF 8
  • CSS3让登陆面板旋转起来

    这里只考虑chrome的兼容 LoginRotate html lt DOCTYPE html gt lt html lang 61 34 en 34 gt lt head gt lt meta charset 61 34 UTF 8 34
  • CSS3 卡片翻转(transform)

    这里只考虑chrome的兼容 card1 html lt DOCTYPE html gt lt html lang 61 34 en 34 gt lt head gt lt meta charset 61 34 UTF 8 34 gt lt
  • 他们的CSS3 3D正方体

    摘自 xff1a 程旭元 所分享的程序 效果图如下 xff1a cube html lt DOCTYPE html gt lt html lang 61 34 zh CN 34 gt lt head gt lt title gt 3D正方体
  • html自定义复选框

    自定义复选框的素材 xff1a icon check circle png icon checked png checkbox html xff08 为了方便起见 xff0c 这里使用到了jQuery xff09 lt DOCTYPE ht
  • CSS3的基本介绍

    知识点记录 xff1a 1 圆角效果 border radius 如 xff1a border radius 10px 所有角都使用半径为10px 的圆角 border radius 5px 4px 3px 2px 四个半径值分别是左上角
  • CSS3选择器(上)

    1 属性选择器 E att 61 val 选择匹配元素 E xff0c 且 E元素定义了属性 att xff0c 其属性值以 val开头的任何字符串 E att 61 val 选择匹配元素 E xff0c 且 E元素定义了属性 att xf
  • CSS3实现曲线阴影和翘边阴影

    效果图如下 xff1a index html lt DOCTYPE html gt lt html lang 61 34 en 34 gt lt head gt lt meta charset 61 34 UTF 8 34 gt lt ti
  • THINKPHP 数据操作方法

    一 ThinkPHP Insert 添加数据 ThinkPHP 内置的 add 方法用于向数据表添加数据 xff0c 相当于 SQL 中的 INSERT INTO 行为 添加数据 add 方法是 CURD xff08 Create Upda
  • PHP文件上传的实现及其介绍

    关于实现及介绍在程序注释中 提交文件的页面 xff1a xff08 可以分别提交到doAction php doAction1 php doAction2 php进行测试 xff09 upload php lt doctype html g
  • PHP单文件上传的过程化函数封装

    提交文件的页面 xff1a upload php lt doctype html gt lt html lang 61 34 en 34 gt lt head gt lt meta charset 61 34 UTF 8 34 gt lt
  • PHP的单个文件上传、多个单文件上传、多文件上传

    单文件上传 upload1 php lt doctype html gt lt html lang 61 34 en 34 gt lt head gt lt meta charset 61 34 UTF 8 34 gt lt title g
  • PHP实现单文件上传、多个单文件上传、多文件上传的过程化封装

    上回提到 PHP的单个文件上传 多个单文件上传 多文件上传 这里给出 三种方式的统一实现 下面先给出各种方式的文件提交页面 xff1a 单个文件上传 upload1 php lt doctype html gt lt html lang 6
  • PHP的单文件上传类

    提交单文件的页面 upload php lt doctype html gt lt html lang 61 34 en 34 gt lt head gt lt meta charset 61 34 UTF 8 34 gt lt title
  • PHP的多文件上传类

    提交表单的页面 upload php lt doctype html gt lt html lang 61 34 en 34 gt lt head gt lt meta charset 61 34 UTF 8 34 gt lt title
  • Nginx负载均衡配置实例详解

    转载自 xff1a http www php100 com html program nginx 2013 0905 5525 html 负载均衡是我们大流量网站要做的一个东西 xff0c 下面我来给大家介绍在Nginx服务器上进行负载均衡
  • 基于Bootstrap使用jQuery实现简单可编辑表格

    editTable js 提供编辑表格当前行 添加一行 删除当前行的操作 xff0c 其中可以设置参数 xff0c 如 xff1a operatePos 用于设置放置操作的列 xff0c 从0开始 xff0c 1表示以最后一列作为放置操作的

随机推荐

  • ThinkPHP 大D方法思想下的JDBC操作数据库D类

    这里我封装出来的D 类 xff0c 是根据 ThinkPHP 中的 D 方法中做出来的 xff0c 其中有些出入的地方 xff0c 我进行了一些个性化的修正 xff0c 如 xff1a ThinkPHP 中操作数据库时 xff0c 需要在配
  • 基于MVC设计模式实现简单PHP框架(雏形)-初期

    xff08 记住 xff1a 这里只是提供思考的过程 xff09 其实这里只是一个我们课的Web实验 课程设计题目统计系统 xff0c 在做实验的过程中起初只是想往MVC靠拢而已 xff0c 却不知不觉地 实现 了基于MVC的简单框架的雏形
  • Rocketmq入门介绍

    目录 一 Rocketmq优势 二 Rocketmq与其他MQ对比 三 MQ基本概念 四 RocketMQ的4个组件 五 集群部署结构 工作流程 xff1a 模块功能特性 xff1a Nameserver Broker 生产者 Produc
  • 我的简单PHP框架——LabPHP

    就我上次提到的 基于MVC设计模式实现简单PHP框架 xff08 雏形 xff09 初期 这次列出我实现的LabPHP简易框架 xff0c 该框架中没有使用任何的模板引擎 xff0c 所以说要在模板中使用到php变量的话 xff0c 仍然需
  • 我的LabPHP框架的Demo应用——课程设计题目统计系统

    1 界面制作 xff08 为了方便起见 xff0c 这里我采用了Bootstrap 框架制作界面 xff09 xff1b 2 数据库设计 xff0c 正确创建students 表 xff1b admin表 xff1a 3 项目目录结构如下
  • 基于Bootstrap使用jQuery实现输入框组input-group的添加与删除

    注意这里要求使用到Bootstrap框架的输入框组 xff0c 如 xff1a lt div class 61 34 row 34 gt lt div class 61 34 col lg 6 34 gt lt div class 61 3
  • 网页中时光轴的简单实现

    时光轴效果如下 xff1a 鼠标滑过当前项时 xff0c 左侧图标大小变大 xff1a index html lt DOCTYPE html gt lt html lang 61 34 en 34 gt lt head gt lt meta
  • 伸缩自如的时光轴实现

    上回说到简单时间轴的实现 xff0c 这一次针对上回的实现的时光轴 xff0c 增加时光轴收起的功能 为了方便重用 xff0c 我分离css样式和js 使用过程中主要注意一下尽量使用css定义的时光轴样式即可 时光轴收起功能的实现过程可以查
  • 伸缩自如的时光轴实现——改进版

    上回讲到的是时光轴 伸缩自如 的实现 xff0c 如果基于响应式制作的话 xff0c 可能存在着许多潜在的BUG 如 xff1a 窗口变化时 xff0c 时光轴的 收起 和 展开 xff0c 都发生了一些变形 为此 xff0c 对原来的 t
  • 伸缩自如的时光轴实现_样式改版

    针对前几篇文章中实现的 伸缩自如 的时光轴 xff0c 对时光轴的样式进行又一次修改 xff0c 效果如下 xff1a 点击 收起 后 xff1a 修改后的 timeline css xff0c 如下 xff1a vertical time
  • ThinkPHP中的create方法与自动令牌验证

    转载自 xff1a Thinkphp中Create方法深入探究 ThinkPHP中的create方法与自动令牌验证实例教程 Thinkphp中Create方法深入探究 由于工作原因在thinkPHP的create 方法上遇到了问题 xff0
  • web安全之token和CSRF攻击

    上文我转载了两篇关于ThinkPHP令牌验证的文章 xff08 ThinkPHP中的create方法与自动令牌验证 xff09 其中提及到了 token xff0c 这里针对 token 的作用 xff0c 转载了另外两篇文章 xff08
  • java中的==、equals和hashCode以及hashCode生成

    转载自 xff1a xff08 点击打开链接 xff09 前言 java中 61 61 equals hashCode 都和对象的比较有关 xff0c 在java中这三者各有什么用处呢 xff0c 即java中为什么需要设计这三种对象的比较
  • javascript调用微信或QQ扫一扫

    项目里为了体验做的好点 xff0c 想直接通过js调用手机的扫一扫 xff1a 服务的用户主要是通过 xff1a 微信或QQ 之前使用过 微信或QQ的分享 腾讯移动WEB开发平台的 39 对外分享组件接口文档 39 http open mo
  • Java中的反射机制

    获取类的类类型的3种方式 xff0c 以及如何通过类的类类型创建实例对象 xff1f ClassDemo1 java package com reflect public class ClassDemo1 public static voi
  • Java中的自定义注解

    自定义注解 Description java xff08 这里自定义Description注解 xff09 package com ann test import java lang annotation Documented import
  • Java中自定义注解的应用

    来自 慕课网 的学习 我们可以使用自定义注解 xff0c 实现ORM xff0c 即对象 关系的映射 通过自定义注解 xff0c 定义对象对应数据表的属性 xff0c 如表名 xff0c 表字段等 Table java xff08 Tabl
  • Intellij IDEA下的第一个Hibernate项目

    参考 xff1a intellij配置hibernate自动生成hbm xml文件 从零开始用Intellij idea14创建hibernate项目 下面我要讲的创建方式 xff0c 可能更加原生态 xff0c 更加类似于Eclipse下
  • Intellij IDEA使用注解创建Hibernate项目中的OR映射类

    上回说到 xff1a Intellij IDEA下的第一个Hibernate项目 我们需要创建 对象到关系的映射配置文件 xff0c 如 entity hbm xml xff08 其中 entity 是我们将要创建的实体 xff09 下面讲
  • Hibernate中Blob对象类型的使用

    使用Intellij IDEA创建Hibernate项目 xff0c 目录结构如下 xff1a 其中 assets app png 为将要存储的照片 xff0c src hibernate cfg xml 为Hibernate的配置文件 x