Hibernate实现Oracle BLOB的数据读写(1)
开发中文件上传到服务器,一般将文件保存在Web服务器的某个目录下,除非有特殊要求将文件存到数据库中保存。
本文主要基于学习的目的而作。
测试环境:Hibernate3.6.7,Oracle 10g Express,JDK7,Win7
1,数据库脚本
?3,编写实体类User.java?5,测试代码package com.tanlan.hibernate.test;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import org.hibernate.Session;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import com.tanlan.hibernate.entity.User;public class TestUser {public static void main(String[] args) {addUser();//getUserById();//update();}private static void addUser() {User user = new User();user.setName("谭岚");File photo = new File("I:\\1.jpg");try {FileInputStream is = new FileInputStream(photo);ByteArrayOutputStream os = new ByteArrayOutputStream();byte[] temp = new byte[512];int i = 0;while ((i = is.read(temp, 0, temp.length)) != -1) {os.write(temp, 0, temp.length);}os.close();is.close();user.setPhoto(os.toByteArray());} catch (Exception e) {e.printStackTrace();}Session session = openSession();Transaction transaction = session.beginTransaction();session.save(user);transaction.commit();}private static void getUserById() {Session session = openSession();User user = (User) session.get(User.class,"402881e432993eae0132993eb7d20000");byte[] photo = user.getPhoto();try {FileOutputStream os = new FileOutputStream("E:\\111.jpg");os.write(photo);os.close();} catch (Exception e) {e.printStackTrace();}}private static void update() {User user = new User();user.setId("402881e432993eae0132993eb7d20000");user.setName("新名");File photo = new File("I:\\2.jpg");try {FileInputStream is = new FileInputStream(photo);ByteArrayOutputStream os = new ByteArrayOutputStream();byte[] temp = new byte[512];int i = 0;while ((i = is.read(temp, 0, temp.length)) != -1) {os.write(temp, 0, temp.length);}os.close();is.close();user.setPhoto(os.toByteArray());} catch (Exception e) {e.printStackTrace();}Session session = openSession();Transaction transaction = session.beginTransaction();session.update(user);transaction.commit();}private static Session openSession() {Configuration cfg = new Configuration().configure();return cfg.buildSessionFactory().openSession();}}?