用hibernate向oracle读取blob数据类型为并下载到本地

向Oracle读取16进制byte[]数据

这种方法只能处理总大小小于6M的数据(在默认的java虚拟机设置下)。 

①持久化类:

 

public class Mail implements Serializable {
	/**
	 * 主键
	 */
	private int id;
	/**
	 * 即将传入数据库中的文件
	 */
	private byte[] filedata;
/*此处省略get、set*/
}

 ②持久化类与hibernate的映射文件:持久化类.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 package="org.hibernate.auction">
	<class name="com.entity.Mail" table="mail" schema="sr">
		<!-- 主键 -->
		<id name="id" column="id" type="integer">
			<!-- 设置主键的唯一性 -->
			<generator class="assigned"></generator>
		</id>
		<!-- 字段 -->		
		<property name="filedata" type="binary" column="uploadfile"></property>
	</class>
</hibernate-mapping>

 ③HibernateUtil.java文件(这个不用去理解复制下来就可以)   

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

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            sessionFactory = 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;
    }

}

 ④用hibernate来读取并下载到本地:

public class TheMain {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//例行公事的两句,不要忘了任何hibernate操作都要用到的
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tran = session.beginTransaction();
		
		File forDownFile = new File("D:/被下载的数据.jpg");
		//从数据库请求数据
		Mail mail = (Mail) session.load(Mail.class, 4);
//如果不要求下载那么写到这里已经足够
		FileOutputStream fos = null;
		try {
			//载入文件路径
			fos = new FileOutputStream(forDownFile);
			//写入文件数据
			fos.write(mail.getFiledata());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				//一定不要忘了释放资源
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值