Ruhezustand - Bild in Datenbank speichern

Ruhezustand - Bild in Datenbank speichern

Um ein Bild in einer Datenbank zu speichern, müssen Sie eine Tabellenspalte als Blob-Datentyp in MySQL oder als äquivalenten Binär-Typ in einer anderen Datenbank definieren. Im Ruhezustand können Sie eine Byte-Array-Variable zum Speichern der Bilddaten deklarieren.

Laden Sie dieses Beispiel herunter -Hibernate-Image-Example.zip

Hier ist ein Maven-Projekt zur Verwendung von Hibernate, um ein Bild in der MySQL-Tabelle "avatar" zu speichern.

1. Tabellenerstellung

Ein Skript zur Erstellung von Avatar-Tabellen in 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-Abhängigkeit

Hibernate- und MySQL-Abhängigkeit hinzufügen.

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-Modell

Erstellen Sie eine Modellklasse zum Speichern der Avatar-Daten. Der Bilddatentyp ist ein Array von Bytes.

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. Zuordnungsdatei

Erstellen Sie eine Hibernate-Zuordnungsdatei für den Avatar. Der Datentyp für image ist binär.

Avatar.hbm.xml





    
        
            
            
        
        
            
        
    

5. Ruhezustand-Konfigurationsdatei

Ruhezustands-Konfigurationsdatei zum Definieren der Datenbankverbindung und der Ruhezustands-Zuordnungsdatei.

hibernate.cfg.xml




    
        false
        com.mysql.jdbc.Driver
        password
        jdbc:mysql://localhost:3306/example
        root
        org.hibernate.dialect.MySQLDialect
        true
        
    

6. Hilfsprogramm "Ruhezustand"

Eine Hibernate-Dienstprogrammklasse zum Abrufen der Datenbankverbindung.

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. Starte es

Lesen Sie eine Datei „C:\mavan-hibernate-image-mysql.gif“ und speichern Sie sie in der Datenbank, holen Sie sie später aus der Datenbank und speichern Sie sie in einer anderen Bilddatei „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();
    }
}

Erledigt.