要求
對于此示例項目,我們將使用:
- Eclipse IDE (您可以使用自己喜歡的IDE);
- MySQL (您可以使用任何其他數據庫,請確保在需要時更改列類型);
- Hibernate jar和依賴關系(您可以下載帶有所有必需jar的示例項目);
- JUnit –用于測試(示例項目中還包括jar)。
打印屏幕
當我們完成該示例項目的實現時,它應如下所示:

數據庫模型

在開始使用示例項目之前,我們必須將此sql腳本運行到MySQL中 :
DROP SCHEMA IF EXISTS `blog` ;
CREATE SCHEMA IF NOT EXISTS `blog` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
USE `blog` ;-- -----------------------------------------------------
-- Table `blog`.`BOOK`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `blog`.`BOOK` ;CREATE TABLE IF NOT EXISTS `blog`.`BOOK` (`BOOK_ID` INT NOT NULL AUTO_INCREMENT ,`BOOK_NAME` VARCHAR(45) NOT NULL ,`BOOK_IMAGE` MEDIUMBLOB NOT NULL ,PRIMARY KEY (`BOOK_ID`) )
ENGINE = InnoDB;
該腳本將創建一個表BOOK ,我們將在本教程中使用該表。
預訂POJO
我們將在這個項目中使用一個簡單的POJO 。 一本書有一個ID ,一個名稱和一個圖像 ,該圖像由字節數組表示 。
當我們要將圖像持久化到數據庫中時,我們必須使用BLOB類型。 MySQL有一些BLOB的變體,您可以在這里檢查它們之間的區別。 在此示例中,我們將使用Medium Blob ,它可以存儲L + 3個字節,其中L <2 ^ 24 。
確保不要忘記在“ 列”注釋上添加列定義 。
package com.loiane.model;import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;@Entity
@Table(name="BOOK")
public class Book {@Id@GeneratedValue@Column(name="BOOK_ID")private long id;@Column(name="BOOK_NAME", nullable=false)private String name;@Lob@Column(name="BOOK_IMAGE", nullable=false, columnDefinition="mediumblob")private byte[] image;public long getId() {return id;}public void setId(long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public byte[] getImage() {return image;}public void setImage(byte[] image) {this.image = image;}
}
休眠配置
此配置文件包含用于連接數據庫的必需信息。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration><session-factory><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:mysql://localhost/blog</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password">root</property><property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property><property name="connection.pool_size">1</property><property name="show_sql">true</property></session-factory>
</hibernate-configuration>
休眠實用程序
HibernateUtil類有助于從Hibernate配置文件創建SessionFactory 。
package com.loiane.hibernate;import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;import com.loiane.model.Book;public class HibernateUtil {private static final SessionFactory sessionFactory;static {try {sessionFactory = new AnnotationConfiguration().configure().addPackage("com.loiane.model") //the fully qualified package name.addAnnotatedClass(Book.class).buildSessionFactory();} catch (Throwable ex) {System.err.println("Initial SessionFactory creation failed." + ex);throw new ExceptionInInitializerError(ex);}}public static SessionFactory getSessionFactory() {return sessionFactory;}
}
道
在此類中,我們創建了兩種方法:一種將Book實例保存到數據庫中,另一種從數據庫中加載Book實例。
package com.loiane.dao;import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;import com.loiane.hibernate.HibernateUtil;
import com.loiane.model.Book;public class BookDAOImpl {/*** Inserts a row in the BOOK table.* Do not need to pass the id, it will be generated.* @param book* @return an instance of the object Book*/public Book saveBook(Book book){Session session = HibernateUtil.getSessionFactory().openSession();Transaction transaction = null;try {transaction = session.beginTransaction();session.save(book);transaction.commit();} catch (HibernateException e) {transaction.rollback();e.printStackTrace();} finally {session.close();}return book;}/*** Delete a book from database* @param bookId id of the book to be retrieved*/public Book getBook(Long bookId){Session session = HibernateUtil.getSessionFactory().openSession();try {Book book = (Book) session.get(Book.class, bookId);return book;} catch (HibernateException e) {e.printStackTrace();} finally {session.close();}return null;}
}
測試
要對其進行測試,首先我們需要創建一個Book實例,并將圖像設置為image屬性。 為此,我們需要從硬盤驅動器中加載一幅圖像,然后將使用位于images文件夾中的圖像。 然后我們可以調用DAO類并保存到數據庫中。
然后,我們可以嘗試加載圖像。 為了確保它與我們加載的圖像相同,我們將其保存在硬盤中。
package com.loiane.test;import static org.junit.Assert.assertNotNull;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;import com.loiane.dao.BookDAOImpl;
import com.loiane.model.Book;public class TestBookDAO {private static BookDAOImpl bookDAO;@BeforeClasspublic static void runBeforeClass() {bookDAO = new BookDAOImpl();}@AfterClasspublic static void runAfterClass() {bookDAO = null;}/*** Test method for {@link com.loiane.dao.BookDAOImpl#saveBook()}.*/@Testpublic void testSaveBook() {//File file = new File("images\\extjsfirstlook.jpg"); //windowsFile file = new File("images/extjsfirstlook.jpg");byte[] bFile = new byte[(int) file.length()];try {FileInputStream fileInputStream = new FileInputStream(file);fileInputStream.read(bFile);fileInputStream.close();} catch (Exception e) {e.printStackTrace();}Book book = new Book();book.setName("Ext JS 4 First Look");book.setImage(bFile);bookDAO.saveBook(book);assertNotNull(book.getId());}/*** Test method for {@link com.loiane.dao.BookDAOImpl#getBook()}.*/@Testpublic void testGetBook() {Book book = bookDAO.getBook((long) 1);assertNotNull(book);try{//FileOutputStream fos = new FileOutputStream("images\\output.jpg"); //windowsFileOutputStream fos = new FileOutputStream("images/output.jpg");fos.write(book.getImage());fos.close();}catch(Exception e){e.printStackTrace();}}
}
要驗證它是否確實保存,讓我們檢查表Book :

如果我們右鍵單擊...

并選擇查看我們剛剛保存的圖像,我們將看到它:

源代碼下載
您可以從以下位置下載完整的源代碼(或分叉/克隆項目– git ):
Github : https : //github.com/loiane/hibernate-image-example
BitBucket : https : //bitbucket.org/loiane/hibernate-image-example/downloads
編碼愉快!
參考: 如何使用Hibernate加載或保存圖像–來自Loiane Groner博客博客的JCG合作伙伴 Loiane Groner 。
翻譯自: https://www.javacodegeeks.com/2012/05/load-or-save-image-using-hibernate.html