ibatis BLOB 图片上传与显示

这几天仔细看了一下iBATIS的文档,发现2.2后,iBATIS的改变还是挺大的。对于自定义类型支持的也不错,这样对于blob和Clob数据的处理也就简单多了。

不过在spring 中已经提供了很好的实现,所以这又省去了很多的功夫,接下来看看iBATIS是如何支持Clob和blob的。

iBATIS提供了TypeHandler接口,用于处理数据类型,基本的实现类为BaseTypeHandler

在spring 中,提供了AbstractLobTypeHandler作为基础类,并且提供了相应的模版方法,所有的工作由LobHandler处理。

BlobByteArrayTypeHandler 主要用于处理blob类型数据,使用byte[]来映射相应的Blob

ClobStringTypeHandler 用于处理Clob类型数据,使用字符串来映射Clob

有一点需要注意的是,AbstractLobTypeHandler中实现了事务支持,需要用来释放相应的资源,所以一定需要在事务环境中进行。

下面是一个简单的例子:

 
 
  1. public class Food {   
  2. private String content;   
  3.  
  4. private String id;   
  5.  
  6. private byte[] image;   
  7.  
  8. private String name;     
  9.     ...   
  10. }  

xml如下:说明一下,在resultMap中可以通过typeHandler来指定具体的handler.在inline变量中,可以通过handler来定义相应的typeHandler

 
 
  1. ﹤sqlMap namespace="Food"﹥   
  2.      
  3.    ﹤typeAlias alias="Food" type="org.esoft.hdb.bo.Food"/﹥   
  4.    ﹤resultMap id="foodResult" class="Food"﹥   
  5.   ﹤result property="id" column="C_ID"/﹥   
  6.   ﹤result property="name" column="C_NAME"/﹥   
  7.   ﹤result property="content" column="C_content"   
  8.  typeHandler="org.springframework.orm.ibatis.support.ClobStringTypeHandler"/﹥   
  9.   ﹤result property="image" column="C_image"   
  10.  typeHandler="org.springframework.orm.ibatis.support.BlobByteArrayTypeHandler"/﹥   
  11.    ﹤/resultMap﹥   
  12.    ﹤sql id="foodFragment"﹥select C_ID,C_NAME,C_CONTENT,C_IMAGE from T_FOOD﹤/sql﹥   
  13.   ﹤select id="getAll" resultMap="foodResult"﹥   
  14.   ﹤include refid="foodFragment"/﹥   
  15.    ﹤/select﹥   
  16.    ﹤select id="selectById" parameterClass="string" resultMap="foodResult"﹥   
  17.   ﹤include refid="foodFragment"/﹥ where C_ID=#id#﹤/select﹥   
  18.      
  19.    ﹤insert id="insert" parameterClass="Food"﹥ insert into T_FOOD ( C_ID,   
  20.   C_NAME,C_CONTENT, C_IMAGE) values ( #id#,   
  21.   #name#,#content,handler=org.springframework.orm.ibatis.support.ClobStringTypeHandler#,   
  22.   #image,handler=org.springframework.orm.ibatis.support.BlobByteArrayTypeHandler#)   
  23.   ﹤/insert﹥   
  24.      
  25.    ﹤update id="update" parameterClass="Food"﹥ update T_FOOD set C_NAME = #name#,   
  26.   C_CONTENT =   
  27.   #content,handler=org.springframework.orm.ibatis.support.ClobStringTypeHandler#,   
  28.   C_IMAGE =   
  29.   #image,handler=org.springframework.orm.ibatis.support.BlobByteArrayTypeHandler#   
  30.   where C_ID = #id# ﹤/update﹥   
  31.      
  32.    ﹤delete id="deleteById" parameterClass="string"﹥ delete from T_FOOD where C_ID = #id#   
  33.   ﹤/delete﹥   
  34.      
  35. ﹤/sqlMap﹥   
  36.  
  37.  
  38. public interface FoodService {   
  39.  
  40.      
  41. void save(Food food);   
  42. Food get(String id);   
  43. /**   
  44. * @param food   
  45. */   
  46. void update(Food food);   
  47. }   
  48.  
  49. public class FoodServiceImpl implements FoodService {   
  50. private FoodDAO foodDAO;   
  51.  
  52. private DaoCreator creator;   
  53.  
  54. public void setCreator(DaoCreator creator) {   
  55.     this.creator = creator;   
  56. }   
  57.  
  58. protected FoodDAO getFoodDAO() {   
  59.     if (foodDAO == null) {   
  60.    foodDAO = (FoodDAO) creator.createDao(FoodDAO.class, Food.class);   
  61.     }   
  62.     return foodDAO;   
  63. }   
  64.  
  65. public Food get(String id) {   
  66.     return getFoodDAO().get(id);   
  67. }   
  68. public void save(Food food) {   
  69.     getFoodDAO().save(food);   
  70. }   
  71. public void update(Food food) {   
  72.     getFoodDAO().update(food);   
  73. }   
  74.  
  75. }   
  76.  
  77. spring xml 配置:  
  78.    
  79. 。。。   
  80.  ﹤bean id="lobHandler"   
  81.   class="org.springframework.jdbc.support.lob.DefaultLobHandler"/﹥   
  82.      
  83.    ﹤bean id="transactionManager"   
  84.   class="org.springframework.jdbc.datasource.DataSourceTransactionManager"﹥   
  85.   ﹤property name="dataSource" ref="dataSource"/﹥   
  86.    ﹤/bean﹥   
  87.      
  88.    ﹤bean id="sqlMapClient"   
  89.   class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"﹥   
  90.   ﹤property name="dataSource" ref="dataSource"/﹥   
  91.   ﹤property name="configLocation"﹥   
  92.  ﹤value﹥SqlMapConfig.xml﹤/value﹥   
  93.   ﹤/property﹥   
  94.   ﹤property name="lobHandler" ref="lobHandler"/﹥   
  95.    ﹤/bean﹥   
  96.      
  97.    ﹤bean id="daoCreate" class="org.esoft.hdb.ibatis.IbatisDaoCreator"﹥   
  98.   ﹤property name="sqlMapClient" ref="sqlMapClient"/﹥   
  99.    ﹤/bean﹥   
  100.      
  101.    ﹤bean id="foodService" class="org.esoft.hdb.service.FoodServiceImpl"﹥   
  102.   ﹤property name="creator" ref="daoCreate"/﹥   
  103.    ﹤/bean﹥   
  104.      
  105.      
  106.    ﹤aop:config﹥   
  107.   ﹤aop:pointcut id="foodServiceMethods"   
  108.  expression="execution(* org.esoft.hdb.service.FoodService.*(..))"/﹥   
  109.   ﹤aop:advisor advice-ref="txAdvice" pointcut-ref="foodServiceMethods"/﹥   
  110.    ﹤/aop:config﹥   
  111.    ﹤tx:advice id="txAdvice" transaction-manager="transactionManager"﹥   
  112.   ﹤tx:attributes﹥   
  113.  ﹤tx:method name="*" propagation="REQUIRED"/﹥   
  114.   ﹤/tx:attributes﹥   
  115.    ﹤/tx:advice﹥  

简单的测试:

 
 
  1. save :   
  2.     Food food = new Food();   
  3.     food.setPk("1");   
  4.     food.setName("food1");   
  5.     BufferedInputStream in = new BufferedInputStream(getClass()   
  6.   .getResourceAsStream("/1.gif"));   
  7.     byte[] b = FileCopyUtils.copyToByteArray(in);   
  8.     food.setImage(b);   
  9.   in = new BufferedInputStream(getClass().getResourceAsStream(   
  10.   "/hibernate.cfg.xml"));   
  11.     b = FileCopyUtils.copyToByteArray(in);   
  12.     food.setContent(new String(b));   
  13.     foodService.save(food);   
  14. update:   
  15. Food food = foodService.get("1");   
  16.     BufferedInputStream in = new BufferedInputStream(getClass()   
  17.   .getResourceAsStream("/jdbc.properties"));   
  18.     byte[] b = FileCopyUtils.copyToByteArray(in);   
  19.     food.setContent(new String(b));   
  20.     foodService.update(food);   
  21.     food = foodService.get("1");   
  22.     assertNotNull(food.getImage());  

iBATIS操作Blob与Clob的情况就像你介绍到这里,希望对你有所帮助。

=======================================================================

图片显示:

公司用的是ibatis+struts2,所以就练习了ibatis+struts2框架下的文件上传功能,针对了两种方法进行练习,一种是用blob字段保存二进制图片流,另一种是在数据库中保存图片的路径,数据库用的是oracle。先说说将图片保存在数据库中的操作。其实ibatis处理blob字段不像网上说的那么复杂,也就和普通字段一样。

实体类中用到的就是  private byte[] photo这个属性,其对应数据库中的blob字段。

insert操作。

1.jsp页面的代码

<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post">
  <input  type="file" name="photo">
</form>
2.在相应action类中添加如下属性
  private File photo;//得到上传的文件
  private String photoContentType;//得到文件的类型
  private String photoFileName;//得到文件的名称
并设置相应的set和get方法以便得到jsp页面中传入的图片的相应信息。
3.将读取到的photo文件转化为byte[]存放到数据库中(其中twb是实体类的一个引用)
 byte[] byte_photo = FileCopyUtils.copyToByteArray(getPhoto());
     twb.setPhoto(byte_photo);
     itnewsContentService.saveContent(twb);
这样就完成了blob字段的插入。
更新操作和插入类似就只是执行update语句,主要就是数据库数据的回显。
jsp页面中通过下面这句话调用相应的action把数据库的图片通过输出流显示出来。
<img src="news_showphoto.action?nnewsid=<s:property value="#request.tnews.nnewsid"/>">
下面是相应action的代码
TnewscontentWithBLOBs tcb = itnewsContentService
     .findByNewId(new Long(getNnewsid()));
    ServletOutputStream sout = ServletActionContext.getResponse()
     .getOutputStream();
   sout.write(tcb.getPhoto());
   sout.flush();
   sout.close();
接下去的删除操作就是delete一句话
 
现在是在数据库中存放路径的练习,这个就更简单了。
insert操作
1.jsp页面代码如上
2.在action中添加相应属性如上
3.将图片保存在本地并将路径保存在数据库代码如下
String path = "e:/ibatis/photo/hbx/images";
     File file = new File(path);
     if (!file.exists())
      file.mkdirs();
   FileUtils.copyFile(getPhoto(), new File(file, getPhotoFileName()));
   twb.setRealPath(path+"/"+getPhotoFileName());
   itnewsContentService.saveContent(twb);
修改操作和insert操作类似。
img中src的路径改成realpath字段中的内容。
删除就直接delete就可以了。
这些就是基本的上传操作,挺简单的

猜你喜欢

转载自lanapple.iteye.com/blog/1064452