基於Hibernate的圖片資料庫儲存(mysql)

其實是這樣的__發表於2013-12-12
用hibernate架構實現儲存圖片

一般網站在處理使用者上傳圖片時通常採用兩種策略:一是直接把圖片存入資料庫中的Blob欄位;二是資料庫中只儲存圖片的在伺服器上的路徑資訊 ,圖片存放在分門別類的檔案中,使用的時候從資料庫讀取路徑資訊到頁面img元素即可.在此不討論兩種方案的優劣,我只是寫了個hibernate的例子 來實現第一種策略.例子很簡單,t_user表主要兩個欄位,name和photo,其中photo欄位型別為Blob.在此例中資料庫我採用 mysql,oracle的Blob欄位比較特殊,你必須自定義型別,具體的請自行搜尋,這方面的資料很多.

//User.java  

package biz.1cn.hibernate;

import java.io.Serializable;
import java.sql.Blob;

public class User implements Serializable{
private Integer id;
private String name;
private Blob photo;
/**
* @return the id
*/
public User(){
}
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the photo
*/
public Blob getPhoto() {
return photo;
}
/**
* @param photo the photo to set
*/
public void setPhoto(Blob photo) {
this.photo = photo;
}

}

類User有3個屬性,id,name,photo,相應的getter和setter方法以及一個無參建構函式.應該注意的是photo的型別java.sql.Blob,相應的user.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="biz.1cn.hibernate">

<class name="biz.1cn.hibernate.User"
table="t_user"
dynamic-update="true"
dynamic-insert="true"
batch-size="3">
<id name="id"
column="id"
type="java.lang.Integer">
<generator class="native"/>
</id>
<property name="name" column="name" type="java.lang.String" lazy="true"/>
<property name="photo" column="photo" type="java.sql.Blob"/>

</class>

</hibernate-mapping>

對應的hibernate.cfg.xml配置檔案,不再列出,請參照hibernate文件自行設定.
好了,做了這一步,我們寫個測試類來進行單元測試:

package biz.1cn.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import biz.1cn.User;

import junit.framework.TestCase;

public class HibernateTest extends TestCase {
private Session session;
protected void setUp() throws Exception {
try{
Configuration config=new Configuration().configure();
SessionFactory sf=config.buildSessionFactory();
session=sf.openSession();
}catch(HibernateException e){
e.printStackTrace();
}
}

protected void tearDown() throws Exception {
try{
session.close();
}catch(HibernateException e){
e.printStackTrace();
}
}

public void testSave()throws FileNotFoundException,IOException{
User user=new User();
user.setName("jordan");
FileInputStream in=new FileInputStream("C:\\test.gif");
Blob photo=Hibernate.createBlob(in);
user.setPhoto(photo);
Transaction tx=null;
try{
tx=session.beginTransaction();
session.saveOrUpdate(user);
tx.commit();
}catch(HibernateException e){
if(tx!=null)
tx.rollback();
e.printStackTrace();
}finally{
in.close();
}
}
public void testLoad()throws Exception{
try{
User user=(User)session.load(User.class, new Integer(1));
Blob photo=user.getPhoto();
InputStream in=photo.getBinaryStream();
FileOutputStream out=new FileOutputStream("C:\\out\\test2.gif");
byte [] buf=new byte[1024];
int len;
while((len=in.read(buf))!=-1){
out.write(buf, 0, len);
}
in.close();
out.close();
}catch(HibernateException e){
e.printStackTrace();
}
}
}

我們讀取C盤目錄下的test.gif並儲存到資料庫中,然後再取出來寫入C:\out目錄,此時你可以檢視下資料表中photo顯示為blob,表示已經成功存入.值的注意的程式碼片段就是:

FileInputStream in=new FileInputStream("C:\\test.gif");
Blob photo=Hibernate.createBlob(in);

我們這裡是從磁碟中讀取圖片,實際應用中你可以利用上傳元件得到圖片的2進位制資料流,並利用Hibernate.createBlob方法來構造相應的 Blob物件.而取圖片則使用InputStream in=photo.getBinaryStream();這只是個簡單的測試類,如果我想從資料庫中取出圖片並現實在頁面上該如何做呢?其實也很簡單,我 們先要寫一個servlet,在它的service方法中取出圖片,並"畫"到指定頁面上.

package biz.1cn.action;

import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.denny)blue.hibernate.User;


public class Test extends HttpServlet {

/**
* Destruction of the servlet. <br>
*/
private Session session;
public void destroy() {
try{
session.close();
}catch(HibernateException e){
e.printStackTrace();
}
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occure
*/
public void init() throws ServletException {
try{
Configuration config=new Configuration().configure();
SessionFactory sf=config.buildSessionFactory();
session=sf.openSession();
}catch(HibernateException e){
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
{
try{
User user=(User)session.load(User.class, new Integer(1));
Blob photo=user.getPhoto();
InputStream in=photo.getBinaryStream();
OutputStream out=response.getOutputStream();
byte [] buf=new byte[1024];
int len;
while((len=in.read(buf))!=-1){
out.write(buf, 0, len);
}
in.close();
out.close();
}catch(Exception e){
e.printStackTrace();
}
}


}

通過response.getOutputStream取得輸出流,其他就與上段程式碼一致.servlet寫好了,怎麼在頁面呼叫呢?那就更簡單啦,直接在頁面的img標籤的src屬性上呼叫該servlet即可,如:

<img id="test" src="/servlet/Test"/>

簡單的例子,希望對初學者有幫助。

儲存圖片到資料庫還有一種思路:就是利用Hibernate的工具類。先將form表單上傳上來的File轉換為Blob, InputStream in = new FileInputStream(file);

Blob blob = Hibernate.creatBlob(in);

呵呵,簡單吧,我也是研究了才發現的

相關文章