以前一直觉得向数据库中存图片是件挺麻烦的事情,今天自己试了一下也没有想像中的那么麻烦(虽然过程中遇到好几次莫名其妙的异常,最后发现是Oracle的包的问题),得益于Hibernate可以很好的支持java.sql.Blob属性的映射
public static void main(String[] args) {
//获得Spring的上下文对象
ApplicationContext ac = new ClassPathXmlApplicationContext("/applicationContext.xml");
//存图片
PresentDao dao = (PresentDao) ac.getBean("presentDao");
FileInputStream fis = null;
try {
ADPresent p = new ADPresent();
p.setName("世博会吉祥物海宝钥匙扣");
p.setDescription("纪念物品");
p.setPrice(25.5);
p.setQtyRemain(100L);
Blob photo = null;
//将图片读进输入流
fis = new FileInputStream("D:\\1.jpg");
// 转成Blob类型
photo = Hibernate.createBlob(fis);
p.setPhoto(photo);
dao.savePresent(p);
fis.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
==============ADPresent的代码==============
private Long objectRrn;
private String name;
private String description;
private Double price;
private Long qtyRemain;
private Blob photo;
setter/getter方法
==============PresentDao的代码==============
//使用spring的依赖注入获得sessionfactory
private SessionFactory sf;
public ADPresent savePresent(ADPresent present) throws Throwable{
Session session = null;
Transaction tx = null;
try {
session = sf.openSession();
tx = session.beginTransaction();
//使用session的save方法可以持久化Blob属性
session.saveOrUpdate(present);
tx.commit();
} catch (Exception e) {
if(tx!=null)
tx.rollback();
throw e;
} finally{
session.close();
}
return present;
}
在写代码的过程中发生了几次数据库相关的异常信息,在屡次排除失败的情况下尝试更换oracle的类包(原来用的是ojdbc14.jar这个jar包,后来换成了%ORACLE_HOME%\product\10.2.0\db_1\jdbc\lib\下的ojdbc14_g.jar,可能换成其他的也行没有试过),问题竟然解决了(原来是oracle版本的问题)