hibernate处理BLOB例子

本文介绍如何利用Hibernate框架在MySQL数据库中存储和检索二进制大对象(BLOB)数据,如图片文件。通过创建相应的表、配置Hibernate环境、实现Java类与数据库表之间的映射,并演示了如何将图片保存到数据库及从数据库读取图片并在网页上显示。

1.在mysql建立表


    
create table `test`.`testblob`(
        `id` 
int not null auto_increment,
       `
image` blob,
        
primary key (`id`)
    );

    
create unique index `PRIMARYon `test`.`testblob`(`id`);

2.在eclipse中建立工程,并导入hibernate包.生成hibernate.cfg.xml 配置文件和HibernateSessionFactory.java

 

package org.myhibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {
@link http://hibernate.org/42.html }.
 
*/

public class HibernateSessionFactory {

    
/** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     
*/

    
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
    
private static final ThreadLocal threadLocal = new ThreadLocal();
    
private  static Configuration configuration = new Configuration();
    
private static org.hibernate.SessionFactory sessionFactory;
    
private static String configFile = CONFIG_FILE_LOCATION;

    
static {
        
try {
            configuration.configure(configFile);
            sessionFactory 
= configuration.buildSessionFactory();
        }
 catch (Exception e) {
            System.err
                    .println(
"%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }

    }

    
private HibernateSessionFactory() {
    }

    
    
/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  
@return Session
     *  
@throws HibernateException
     
*/

    
public static Session getSession() throws HibernateException {
        Session session 
= (Session) threadLocal.get();

        
if (session == null || !session.isOpen()) {
            
if (sessionFactory == null{
                rebuildSessionFactory();
            }

            session 
= (sessionFactory != null? sessionFactory.openSession()
                    : 
null;
            threadLocal.set(session);
        }


        
return session;
    }


    
/**
     *  Rebuild hibernate session factory
     *
     
*/

    
public static void rebuildSessionFactory() {
        
try {
            configuration.configure(configFile);
            sessionFactory 
= configuration.buildSessionFactory();
        }
 catch (Exception e) {
            System.err
                    .println(
"%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }

    }


    
/**
     *  Close the single hibernate session instance.
     *
     *  
@throws HibernateException
     
*/

    
public static void closeSession() throws HibernateException {
        Session session 
= (Session) threadLocal.get();
        threadLocal.set(
null);

        
if (session != null{
            session.close();
        }

    }


    
/**
     *  return session factory
     *
     
*/

    
public static org.hibernate.SessionFactory getSessionFactory() {
        
return sessionFactory;
    }


    
/**
     *  return session factory
     *
     *    session factory will be rebuilded in the next call
     
*/

    
public static void setConfigFile(String configFile) {
        HibernateSessionFactory.configFile 
= configFile;
        sessionFactory 
= null;
    }


    
/**
     *  return hibernate configuration
     *
     
*/

    
public static Configuration getConfiguration() {
        
return configuration;
    }


}

 

 

 

<?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"
>

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
    
<property name="connection.username">root</property>
    
<property name="connection.url">
        jdbc:mysql://localhost:3306/test
    
</property>
    
<property name="dialect">
        org.hibernate.dialect.MySQLDialect
    
</property>
    
<property name="myeclipse.connection.profile">MySql</property>
    
<property name="connection.password">数据库密码</property>
    
<property name="connection.driver_class">
        com.mysql.jdbc.Driver
    
</property>
    
<property name="show_sql">true</property>
    
<mapping resource="org/myhibernate/Testblob.hbm.xml" />

</session-factory>

</hibernate-configuration>

 3.生成类与表之间的映射,并生成bean

 

package org.myhibernate;

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 java.sql.SQLException;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {
    
public void addImage(Testblob testblob) {
        Session session 
= HibernateSessionFactory.getSession();
        FileInputStream images
=null;
        Blob img
=null;
        
try {
            images
=new FileInputStream("c:/1.jpg");
        }
 catch (FileNotFoundException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }

        
try {
            img
=Hibernate.createBlob(images);
        }
 catch (IOException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }

        testblob.setImage(img);
        Transaction tx
=session.beginTransaction();
        
try{
            session.save(testblob);
        }

        
catch(Exception ex){
            System.out.println(
"保存异常出现");
            ex.printStackTrace();
        }

        tx.commit();
        session.close();
    }

    
    
public void SeeImage(){
        Session session 
= HibernateSessionFactory.getSession();
        Testblob testblob
=(Testblob)session.load(Testblob.classnew Integer(1));
        Blob img
=testblob.getImage();
        FileOutputStream output
=null;
        InputStream is
=null;
        
try {
            is
=img.getBinaryStream();
        }
 catch (SQLException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }

        
try {
            output
=new FileOutputStream("c:/2.jpg");
        }
 catch (FileNotFoundException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }

        
byte[] byt=new byte[102400];
        
int len;
        
try {
            
while((len=is.read(byt))!=-1){
                output.write(byt,
0,len);
            }

        }
 catch (IOException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }

        
try{
            output.close();
            is.close();
        }
catch(Exception ex){
            ex.printStackTrace();
        }

    }

}

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    
<class name="org.myhibernate.Testblob" table="testblob">
        
<id name="id" type="java.lang.Integer">
            
<column name="id" />
            
<generator class="native" />
        
</id>
        
<property name="image" type="java.sql.Blob">
            
<column name="image" />
        
</property>
    
</class>
</hibernate-mapping>

4.写个servlet

 

package org.myhibernate;

import java.io.IOException;
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.Session;

public class TestServlet extends HttpServlet {
    
public TestServlet() {
        
super();
    }

    
public void destroy() {
        
super.destroy(); // Just puts "destroy" string in log
        
// Put your code here
    }


        
public void doGet(HttpServletRequest request, HttpServletResponse response)
            
throws ServletException, IOException {
        doPost(request, response);
    }


        
public void doPost(HttpServletRequest request, HttpServletResponse response)
            
throws ServletException, IOException {
                Session session 
= HibernateSessionFactory.getSession();
        Testblob testblob 
= (Testblob) session.load(Testblob.class,
                
new Integer(1));
        Blob img 
= testblob.getImage();
        OutputStream output 
= null;
        
try {
            output 
= response.getOutputStream();// 得到输出流
        }
 catch (IOException ex1) {
            ex1.printStackTrace(System.out);
        }

        
try {
            
int len=(int)img.length();
            
byte[] photo = img.getBytes(1,len);// 从数据库中读出文件
            if (photo != null && photo.length > 0{
                output.write(photo); 
// 输出到网页上
            }

        }
 catch (Exception ex) {
            ex.printStackTrace(System.out);
        }

    }


        
public void init() throws ServletException {
        
// Put your code here
    }


}

 

5.用一个index.jsp来作为测试的页面

 

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  
<head>
    
<base href="<%=basePath%>">
    
    
<title>My JSP 'index.jsp' starting page</title>
    
<meta http-equiv="pragma" content="no-cache">
    
<meta http-equiv="cache-control" content="no-cache">
    
<meta http-equiv="expires" content="0">    
    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    
<meta http-equiv="description" content="This is my page">
    
<!--
    
<link rel="stylesheet" type="text/css" href="styles.css">
    
-->
  
</head>
  
  
<body>
    
<form action="<%=basePath%>servlet/TestServlet" method="post">
       
<input type="submit" value="提交"/>
    
</form>
  
</body>
</html>
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值