Hibernate –画像をデータベースに保存します
データベースに画像を保存するには、テーブル列をMySQLのblobデータ型、または他のデータベースの同等のバイナリ型として定義する必要があります。 Hibernate側では、バイト配列変数を宣言して画像データを保存できます。
この例をダウンロード–Hibernate-Image-Example.zip
これは、Hibernateを使用して画像をMySQLの ‘avatar‘テーブルに保存するMavenプロジェクトです。
1. テーブル作成
MySQLのアバターテーブル作成スクリプト。
CREATE TABLE `example`.`avatar` ( `AVATAR_ID` int(10) unsigned NOT NULL AUTO_INCREMENT, `IMAGE` blob NOT NULL, PRIMARY KEY (`AVATAR_ID`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
2. Mavenの依存関係
HibernateとMySQLの依存関係を追加します。
pom.xml
4.0.0 com.example.common HibernateExample jar 1.0-SNAPSHOT HibernateExample http://maven.apache.org junit junit 3.8.1 test mysql mysql-connector-java 5.1.9 hibernate hibernate3 3.2.3.GA dom4j dom4j 1.6.1 commons-logging commons-logging 1.1.1 commons-collections commons-collections 3.2.1 cglib cglib 2.2
3. アバターモデル
モデルクラスを作成して、アバターデータを保存します。 画像データ型はバイトの配列です。
Avatar.java
package com.example.common;
public class Avatar implements java.io.Serializable {
private Integer avatarId;
private byte[] image;
public Avatar() {
}
public Avatar(byte[] image) {
this.image = image;
}
public Integer getAvatarId() {
return this.avatarId;
}
public void setAvatarId(Integer avatarId) {
this.avatarId = avatarId;
}
public byte[] getImage() {
return this.image;
}
public void setImage(byte[] image) {
this.image = image;
}
}
4. マッピングファイル
アバター用のHibernateマッピングファイルを作成します。 画像のデータ型はバイナリです。
Avatar.hbm.xml
5. Hibernate設定ファイル
データベース接続とHibernateマッピングファイルを定義するHibernate構成ファイル。
hibernate.cfg.xml
false com.mysql.jdbc.Driver password jdbc:mysql://localhost:3306/example root org.hibernate.dialect.MySQLDialect true
6. Hibernateユーティリティ
データベース接続を取得するためのHibernateユーティリティクラス。
HibernateUtil.java
package com.example.persistence;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return 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;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
7. それを実行します
ファイル「C:\mavan-hibernate-image-mysql.gif」を読み取ってデータベースに保存し、後でデータベースから取得して別のイメージファイル「C:\test.gif」に保存します。
package com.example.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.hibernate.Session;
import com.example.persistence.HibernateUtil;
public class App
{
public static void main( String[] args )
{
System.out.println("Hibernate save image into database");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
//save image into database
File file = new File("C:\\mavan-hibernate-image-mysql.gif");
byte[] bFile = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
//convert file into array of bytes
fileInputStream.read(bFile);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Avatar avatar = new Avatar();
avatar.setImage(bFile);
session.save(avatar);
//Get image from database
Avatar avatar2 = (Avatar)session.get(Avatar.class, avatar.getAvatarId());
byte[] bAvatar = avatar2.getImage();
try{
FileOutputStream fos = new FileOutputStream("C:\\test.gif");
fos.write(bAvatar);
fos.close();
}catch(Exception e){
e.printStackTrace();
}
session.getTransaction().commit();
}
}
完了しました。