Hibernate保存图片 文件 到数据库

为了在数据库中保存文件,需要在数据库中定义二进制指端blob. 有的数据库也有 image 类型也可以。在hibernate 实体类 这一边, 定义 类型为  byte[] 就可以。做一个简单的例子测试

1. 在mysql 中创建表
程序代码 程序代码

Create TABLE  `yihaomen`.`avatar` (
  `AVATAR_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `IMAGE` BLOB NOT NULL,
  PRIMARY KEY (`AVATAR_ID`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;


2. 项目所需要的 maven 依赖
程序代码 程序代码

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.yihaomen.common</groupId>
  <artifactId>HibernateExample</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>HibernateExample</name>
  <url>http://maven.apache.org</url>
  <dependencies>

        <dependency>
               <groupId>junit</groupId>
               <artifactId>junit</artifactId>
               <version>3.8.1</version>
               <scope>test</scope>
        </dependency>

        <!-- MySQL database driver -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.9</version>
    </dependency>

    <!-- Hibernate framework -->
    <dependency>
        <groupId>hibernate</groupId>
        <artifactId>hibernate3</artifactId>
        <version>3.2.3.GA</version>
    </dependency>

    <!-- Hibernate library dependecy start -->
    <dependency>
        <groupId>dom4j</groupId>
        <artifactId>dom4j</artifactId>
        <version>1.6.1</version>
    </dependency>

    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.1.1</version>
    </dependency>

    <dependency>
        <groupId>commons-collections</groupId>
        <artifactId>commons-collections</artifactId>
        <version>3.2.1</version>
    </dependency>

    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>2.2</version>
    </dependency>
    <!-- Hibernate library dependecy end -->

  </dependencies>
</project>


3. model 层编写
程序代码 程序代码

public class Avatar implements java.io.Serializable {

    private Integer avatarId;
    private byte[] image;

    public Avatar() {
    }

    public Avatar(byte[] image) {
        this.image = image;
    }

    public Integer getAvatarId() {
        return this.avatarId;
    }

    public void setAvatarId(Integer avatarId) {
        this.avatarId = avatarId;
    }

    public byte[] getImage() {
        return this.image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }

}


4. Hiberante mapping 配置文件 Avatar.hbm.xml
程序代码 程序代码

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.yihaomen.common.Avatar" table="avatar">
        <id name="avatarId" type="java.lang.Integer">
            <column name="AVATAR_ID" />
            <generator class="identity" />
        </id>
        <property name="image" type="binary">
            <column name="IMAGE" not-null="true" />
        </property>
    </class>
</hibernate-mapping>


5. Hibernate 配置文件 hibernate.cfg.xml
程序代码 程序代码

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/yihaomen</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <mapping resource="com/yihaomen/common/Avatar.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>


6. Hibernate 工具类
程序代码 程序代码


import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }

}


7. 编写测试代码,并进行测试
程序代码 程序代码

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.hibernate.Session;
import com.mkyong.persistence.HibernateUtil;

public class App
{
    public static void main( String[] args )
    {
        System.out.println("Hibernate save image into database");
        Session session = HibernateUtil.getSessionFactory().openSession();

        session.beginTransaction();

        //save image into database
        File file = new File("C:\\mavan-hibernate-image-mysql.gif");
        byte[] bFile = new byte[(int) file.length()];

        try {
         FileInputStream fileInputStream = new FileInputStream(file);
         //convert file into array of bytes
         fileInputStream.read(bFile);
         fileInputStream.close();
        } catch (Exception e) {
         e.printStackTrace();
        }

        Avatar avatar = new Avatar();
        avatar.setImage(bFile);

        session.save(avatar);

        //Get image from database
        Avatar avatar2 = (Avatar)session.get(Avatar.class, avatar.getAvatarId());
        byte[] bAvatar = avatar2.getImage();

        try{
            FileOutputStream fos = new FileOutputStream("C:\\test.gif");
            fos.write(bAvatar);
            fos.close();
        }catch(Exception e){
            e.printStackTrace();
        }

        session.getTransaction().commit();
    }
}


由此可见,hibernate 保存文件到数据库,起始并不难,其实就是保存 byte[] , 注意到这点,应该就好处理了。

除非申明,文章均为一号门原创,转载请注明本文地址,谢谢!
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags:
相关日志:
评论: 0 | 引用: 0 | 查看次数: -
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.