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

/***//**
*
@paramargs
*
@throwsException
*/

publicstaticvoidmain(String[]args)throwsException...{
//insert();
show();
}

publicstaticPersonshow()throwsException...{
Sessions
=null;
Transactiontran
=null;
Stringhql
="fromPerson";
try...{
s
=HbnUtil.getSession();
tran
=s.beginTransaction();
Queryquery
=s.createQuery(hql);
Listlist
=query.list();
System.out.println(list.size());
inti=0;
for(Personperson:(List<Person>)list)...{
intlen=(int)person.getBl().length();
byte[]temp=person.getBl().getBytes(1,len);
Stringdir
="c:/temp/temp_"+person.getName()+".jpg";
FileOutputStreamfos
=newFileOutputStream(dir);
fos.write(temp);
}

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

returnnull;
}

publicstaticvoidinsert()throwsException...{
Sessions
=null;
Transactiontran
=null;

try...{
FileInputStreamfis
=newFileInputStream("c:/temp/112.jpg");
System.out.println(fis.available());
Personperson
=newPerson();
person.setName(
"teng");
person.setBl(Hibernate.createBlob(fis));

s
=HbnUtil.getSession();
tran
=s.beginTransaction();
s.save(person);
fis.close();
tran.commit();
}
catch(HibernateExceptione)...{
e.printStackTrace();
tran.rollback();
}
finally...{
HbnUtil.releaseSession(s);
}

}


}

你可能感兴趣的:(java,sql,c,Hibernate,mysql)