hibernate+mysql图片读取

在网上找了一些资料,自己又试验了一下,成功了!

大概过程就是,把图片文件用inputstream读取出来, 变成字节码文件,把字节码存储进数据库,在数据库里用CLOB数据类型存储图片。下面是代码:

 

package  image;

import  java.awt.image.BufferedImage;
import  java.io.FileInputStream;
import  java.io.FileNotFoundException;
import  java.io.FileOutputStream;
import  java.io.InputStream;
import  java.sql.SQLException;
import  java.util.Date;
import  java.util.List;

import  javax.imageio.ImageIO;

import  many2many.HbnUtil;
import  many2many.Student;

import  org.hibernate.Hibernate;
import  org.hibernate.HibernateException;
import  org.hibernate.Query;
import  org.hibernate.Session;
import  org.hibernate.Transaction;

public   class  Test  {

    
/**
     * 
@param args
     * 
@throws Exception 
     
*/

    
public static void main(String[] args) throws Exception {
        
//insert();
        show();
    }

    
public static Person show() throws Exception{
        Session s
=null;
        Transaction tran
=null;
        String hql
="from Person";
        
try{
            s
=HbnUtil.getSession();        
            tran
=s.beginTransaction();
            Query query
=s.createQuery(hql);
            List list
=query.list();
            System.out.println(list.size());
            
int i=0;
            
for(Person person:(List<Person>) list){
                    
int len=(int) person.getBl().length();                    
                    
byte[] temp=person.getBl().getBytes(1, len);
                    String dir
="c:/temp/temp_"+person.getName()+".jpg";
                    FileOutputStream fos
=new FileOutputStream(dir);
                    fos.write(temp);
            }

            tran.commit();
        }
 catch (HibernateException e) {
            e.printStackTrace();
            tran.rollback();
        }
finally{
            HbnUtil.releaseSession(s);
        }

        
return null;        
    }

    
public static void insert() throws Exception{
        Session s
=null;
        Transaction tran
=null;
        
        
try{
            FileInputStream fis
=new FileInputStream("c:/temp/112.jpg");
            System.out.println(fis.available());            
            Person person
=new Person();
            person.setName(
"teng");
            person.setBl(Hibernate.createBlob(fis));
            
            s
=HbnUtil.getSession();        
            tran
=s.beginTransaction();
            s.save(person);    
            fis.close();        
            tran.commit();
        }
 catch (HibernateException e) {
            e.printStackTrace();
            tran.rollback();
        }
finally{
            HbnUtil.releaseSession(s);
        }
            
    }


}

你可能感兴趣的:(hibernate+mysql图片读取)