Este Tutorial básico irá nos orientar como salvar e carregar uma imagem a partir de banco de dados (MySQL), utilizando Hibernate e Java. Requisitos: Eclipse IDE ( ou qualquer IDE com Java); MySQL (você pode usar qualquer outro banco de dados, certifique-se de alterar o tipo de coluna, se necessário); Hibernate (este é o 4.1.6); PrintScreen Quando implementar seu projeto, ele deve ser parecido com isto: Database Model Primeiro passo, vamos criar o BD, pode ser com este script SQL em MySQL: 01 DROP SCHEMA IF EXISTS `blog` ;
CREATE SCHEMA IF NOT EXISTS `blog` DEFAULT CHARACTER SET latin1 02 COLLATE latin1_swedish_ci ; 03 USE `blog` ; 04 05 -- ----------------------------------------------------- 06 -- Table `blog`.`book` 07 -- ----------------------------------------------------- 08 DROP TABLE IF EXISTS `blog`.`book` ; 09 10 CREATE TABLE IF NOT EXISTS `blog`.`book` ( 11 `BOOK_ID` INT NOT NULL AUTO_INCREMENT, 12 `BOOK_NAME` VARCHAR(45) NOT NULL, 13 `BOOK_IMAGE` MEDIUMBLOB NOT NULL, 14 PRIMARY KEY (`BOOK_ID`) ) 15 ENGINE = InnoDB; Criamos a tabela BOOK bem simples para usar neste tutorial. Book POJO Vamos usar um POJO simples. Um livro tem um ID, e um nome e uma imagem, a qual é representada por um conjunto de bytes. Como vamos persistir uma imagem no banco de dados, temos que usar o tipo BLOB. MySQL tem algumas variações de BLOBs, é possível verificar a diferença entre eles aqui. A diferença entre alguns tipos de do Mysql são: TINYTEXT - 255 bytes TEXT - 65535 bytes MEDIUMTEXT - 16,777,215 bytes (2^24-1) LONGTEXT - 4G bytes (2^32 1) TINYBLOB - 255 bytes BLOB - 65535 bytes MEDIUMBLOB - 16,777,215 bytes (2^24-1) LONGBLOB - 4G bytes (2^32 1) Neste exemplo, vamos usar o Blob Médio, neste trecho de código: 01 package com.test.model; 02 03 import javax.persistence.column;
04 import javax.persistence.entity; 05 import javax.persistence.generatedvalue; 06 import javax.persistence.id; 07 import javax.persistence.lob; 08 import javax.persistence.table; 09 10 @Entity 11 @Table(name="BOOK") 12 public class Book { 13 14 @Id 15 @GeneratedValue 16 @Column(name="BOOK_ID") 17 private long id; 18 19 @Column(name="BOOK_NAME", nullable=false) 20 private String name; 21 22 @Lob 23 @Column(name="BOOK_IMAGE", nullable=false, columndefinition="mediumblob") 24 private byte[] image; 25 26 public long getid() { 27 return id; 28 29 30 public void setid(long id) { 31 this.id = id; 32 33 34 public String getname() { 35 return name; 36 37 38 public void setname(string name) { 39 this.name = name; 40 41 42 public byte[] getimage() { 43 return image;
44 45 46 public void setimage(byte[] image) { 47 this.image = image; 48 49 Hibernate Config Este arquivo de configuração contém as informações necessárias para conectar ao banco de dados (hibernate.cfg.xml). <?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</proper ty> <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> Hibernate Util A classe HibernateUtil ajuda a criar a SessionFactory do arquivo de configuração Hibernate. package com.test.hibernate; import org.hibernate.sessionfactory; import org.hibernate.cfg.annotationconfiguration; import com.test.model.book; public class HibernateUtil { private static final SessionFactory sessionfactory; static {
try { sessionfactory = new AnnotationConfiguration().configure().addPackage("com.test.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; DAO Nesta classe, criamos dois métodos: um para salvar uma instância Book no banco de dados e outro para carregar uma instância Book, do banco de dados. package com.test.dao; import org.hibernate.hibernateexception; import org.hibernate.session; import org.hibernate.transaction; import com.test.hibernate.hibernateutil; import com.test.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(); 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) { finally { session.close(); return null; Test Para testá-lo, primeiro é necessário criar uma instância de Book e definir uma imagem para o atributo de imagem. Para isso, é preciso carregar uma imagem do Computador, localizado na pasta de imagens. Então, podemos chamar a classe DAO e salvar no banco de dados. Então, podemos tentar carregar a imagem. Só para ter certeza que é a mesma imagem que carregamos e salvá-lo no BD. package com.test.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.test.dao.bookdaoimpl; import com.test.model.book; public class TestBookDAO { private static BookDAOImpl bookdao; @BeforeClass public static void runbeforeclass() { bookdao = new BookDAOImpl(); @AfterClass public static void runafterclass() { bookdao = null;
/** * Test method for {@link com.test.dao.bookdaoimpl#savebook(). @Test public void testsavebook() { //File file = new File("images\\extjsfirstlook.jpg"); //windows File 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) { 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.test.dao.bookdaoimpl#getbook(). @Test public void testgetbook() { Book book = bookdao.getbook((long) 1); assertnotnull(book); try{ //FileOutputStream fos = new FileOutputStream("images\\output.jpg"); //windows FileOutputStream fos = new FileOutputStream("images/output.jpg"); fos.write(book.getimage()); fos.close(); catch(exception e){ Para verificar se ele foi realmente salvou, vamos verificar a tabela do Book: