hibernateアクセスピクチャ例(mysql)


一般的なウェブサイトはユーザーが画像をアップロードすることを処理する時通常2つの策略を採用します:1つは直接画像をデータベースの中のBlobフィールドに格納します;2つ目は、データベースに画像のみを格納するサーバ上のパス情報であり、画像は分類されたファイルに格納され、使用時にデータベースからパス情報をページimg要素に読み出すだけでよい.ここでは2つのスキームの優劣を議論せず、hibernateの例を書いて第1のポリシーを実現しただけである.例は簡単で、t_user表の主な2つのフィールド、nameとphoto、その中のphotoフィールドのタイプはBlobです.この例ではデータベースはmysqlを採用しています.oracleのBlobフィールドは特殊です.タイプをカスタマイズする必要があります.具体的には自分で検索してください.この方面の資料はたくさんあります.//User.java  
package com.denny_blue.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の方法と1つのパラメトリック構造の関数があります.注意すべきなのは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="com.denny_blue.hibernate">

<class name="com.denny_blue.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ドキュメントを参照して自分で設定してください.OK、このステップでは、テストクラスを書いてユニットテストを行います.
package com.denny_blue.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 com.denny_blue.hibernate.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 com.easyjf.asp.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"/>