向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(); } } } }