博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SSH框架中向数据库存取图片
阅读量:4054 次
发布时间:2019-05-25

本文共 2046 字,大约阅读时间需要 6 分钟。

 以前一直觉得向数据库中存图片是件挺麻烦的事情,今天自己试了一下也没有想像中的那么麻烦(虽然过程中遇到好几次莫名其妙的异常,最后发现是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版本的问题)

转载地址:http://umtci.baihongyu.com/

你可能感兴趣的文章
三、优化分类
查看>>
四、Mybatis解决字段名与实体类属性名不相同的冲突
查看>>
五、Mybtis实现关联表查询
查看>>
六、Mybatis动态SQL和模糊查询
查看>>
七、Mybatis调用存储过程
查看>>
八、Mybatis一级缓存和二级缓存
查看>>
九、Spring集成Mybatis
查看>>
Eclipse调优、设置大全
查看>>
一、SpringMVC入门,实现HelloWorld
查看>>
二、@ResquestMapping
查看>>
三、@PathVariable
查看>>
一、Spring核心机制:依赖注入
查看>>
Spring应用于组件注册的注解
查看>>
Log4和self4j整合使用
查看>>
多线程基础(一)
查看>>
线程之间的通信(二)
查看>>
同步类容器和并发类容器(三)
查看>>
Queue(四)
查看>>
多线程设计模式(五)
查看>>
Executor(六)
查看>>