Java Hibernate Oracle存储大文件

12 篇文章 0 订阅
10 篇文章 0 订阅

http://howtodoinjava.com/2013/08/30/hibernate-example-of-insertselect-blob-from-database/


Lets take an example, in which, I am inserting “test.png” image from windows C drive to database (MySQL). Then I will read the image data again from database and store it to different location.

Hibernate entity

Please note, I have declared the data field as byte[].

<span style="font-size:14px;">@Entity
@Table(name = "TBL_IMAGES")
public class ImageWrapper implements Serializable {
     
    private static final long serialVersionUID = 1L;
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", unique = true, nullable = false)
    private Integer id;
     
    @Column(name = "IMAGE_NAME", unique = false, nullable = false, length = 100)
    private String imageName;
     
    @Column(name = "DATA", unique = false, nullable = false, length = 100000)
    private byte[] data;
     
    //Getters and Setters
}</span>


Inserting blob data into database

Let’s look at the code:

Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
     
File file = new File("C:\test.png");
byte[] imageData = new byte[(int) file.length()];
 
try {
    FileInputStream fileInputStream = new FileInputStream(file);
    fileInputStream.read(imageData);
    fileInputStream.close();
} catch (Exception e) {
    e.printStackTrace();
}
 
ImageWrapper image = new ImageWrapper();
image.setImageName("test.jpeg");
image.setData(imageData);
 
session.save(image);    //Save the data
 
session.getTransaction().commit();
HibernateUtil.shutdown();

After executing above code, you can verify that a table into database is created if it’s not already there. And one BLOB column is created to hold the image data.



Reading the blob data from database

This is simple, and in fact you do not need to do anything extra. Above entity definition will work fine.

Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
 
ImageWrapper imgNew = (ImageWrapper)session.get(ImageWrapper.class, 1);
byte[] bAvatar = imgNew.getData();
 
try{
    FileOutputStream fos = new FileOutputStream("C:\temp\test.png");
    fos.write(bAvatar);
    fos.close();
}catch(Exception e){
    e.printStackTrace();
}
 
session.getTransaction().commit();
HibernateUtil.shutdown();

Hibernate configuration

For reference, This is the configuration I am using for this example:

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.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">create</property>
        <mapping class="hibernate.test.dto.ImageWrapper"></mapping>
    </session-factory>
</hibernate-configuration>

Also below is the code for HibernateUtil.java

HibernateUtil.java

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();
      
    @SuppressWarnings("deprecation")
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().configure(new File
                    ("D:\Latest Setup\eclipse_juno_workspace\hibernate-test-project\hibernate.cgf.xml"))
                    .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() {
        getSessionFactory().close();
    }
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值