Ibatis + Spring 操作 Blob 详解

转自:http://blog.csdn.net/cwb1128/article/details/4342141

 

一:Java工程环境介绍 

(1) 工程目录结构

Ibatis + Spring 操作 Blob 详解_第1张图片 

(2) Oracle9i + Oracle10g的驱动 + jdk1.4

 

(3) 用到的jar包如下:

 

Ibatis + Spring 操作 Blob 详解_第2张图片

(4) 数据库表结构

create table IBATIS_BLOB
(
  ID      VARCHAR2(5) not null,
  TITLE   VARCHAR2(50),
  CONTENT BLOB
)

二:主要代码如下

(1) IbatisBlob.java

package cn.com.victorysoft.vo;

public class IbatisBlob {
 private String id;
 private String title;
 private byte[] content;
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public byte[] getContent() {
  return content;
 }
 public void setContent(byte[] content) {
  this.content = content;
 }
}

(2) ibatisblob-sqlmap.xml

<sqlMap namespace="ibatisblob">
 <typeAlias alias="ibatisblob" type="cn.com.victorysoft.vo.IbatisBlob" />
 <select id="getIbatisBlobById" parameterClass="ibatisblob" resultClass="ibatisblob">
  select * from IBATIS_BLOB where
  <dynamic prepend=" ">
  <isNotNull prepend="and" property="id">
     id = #id#
  </isNotNull>
  </dynamic>
 </select>
 <insert id="insert" parameterClass="ibatisblob">
  <selectKey resultClass="string" keyProperty="id">
   select IBATISBLOB_SQ.nextval as id from dual
  </selectKey>
  insert into IBATIS_BLOB(id,content,title) values(#id#,#content:BLOB#,#title#)
 </insert>
 <insert id="update" parameterClass="ibatisblob">
  update IBATIS_BLOB set title = #title# ,content= #content:BLOB#
  where id = #id#
 </insert>
</sqlMap>

(3) SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
    "
http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
 <settings cacheModelsEnabled="true" enhancementEnabled="true"
  lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="32"
  maxSessions="10" maxTransactions="5" useStatementNamespaces="false" /> 

<typeHandler jdbcType="BLOB" javaType="[B" callback="org.springframework.orm.ibatis.support.BlobByteArrayTypeHandler" />
 <sqlMap
  resource="cn/com/victorysoft/sqlmap/ibatisblob-sqlmap.xml" />
</sqlMapConfig>

说明:红色部分为处理BLOB 类型的TypeHandler 实现类。

(4) beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "
http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName">
      <value>oracle.jdbc.driver.OracleDriver</value>
    </property>
    <property name="url">
      <value>jdbc:oracle:thin:@localhost:1521:ora</value>
    </property>
    <property name="username">
      <value>test</value>
    </property>
    <property name="password">
      <value>test</value>
    </property>
  </bean>
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource">
   <ref bean="dataSource"/>
  </property>
 </bean>
 <bean id="transactionManagerRootProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true">
  <property name="transactionManager">
   <ref bean="transactionManager"/>
  </property>
  <property name="proxyTargetClass">
   <value>false</value>
  </property>
  <property name="transactionAttributes">
   <props>
    <prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>

    <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
    <prop key="select*">PROPAGATION_REQUIRED,readOnly</prop>
   </props>
  </property>
 </bean>
  <bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor" lazy-init="true" />   
    <bean id="oracleLobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler" lazy-init="true">  
     <property name="nativeJdbcExtractor">  
         <ref local="nativeJdbcExtractor" />  
     </property>  
 </bean>
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
 <property name="configLocation" value="SqlMapConfig.xml"/>
 <property name="dataSource" ref="dataSource"/>
 <property name="lobHandler">  
         <ref local="oracleLobHandler"/>  
     </property>
</bean>
<bean id="dataAccess" class="cn.com.victorysoft.dataaccess.impl.DataAccess">
   <property name="sqlMapClient" ref="sqlMapClient"/>
</bean>
<bean id="batisBlobDAOSub" class="cn.com.victorysoft.dao.impl.IBatisBlobDAOImpl">
   <property name="dataAccess" ref="dataAccess"/>
</bean>
<bean id="batisBlobDAO" parent="transactionManagerRootProxy">
  <property name="target">
   <ref bean="batisBlobDAOSub" />
  </property>
</bean>
</beans>

说明:Spring对LOB的支持是在事务的环境中,所以操作LOB的DAO必须受事务的管理。如果不放在事务的环境中,会报如下异常:

Caused by: java.lang.IllegalStateException: Spring transaction synchronization needs to be active for setting values

(5) 测试类代码 MainTest.java

package cn.com.victorysoft.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.FileCopyUtils;
import cn.com.victorysoft.dao.IBatisBlobDAO;
import cn.com.victorysoft.vo.IbatisBlob;

public class MainTest {
 public static void main(String[] args) throws Exception {
  ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
  IBatisBlobDAO  batisBlobDAO = (IBatisBlobDAO)ctx.getBean("batisBlobDAO");
  //****************插入图片开始*************
  IbatisBlob batisBlob = new IbatisBlob();
  batisBlob.setTitle("mytitle");
  File file = new File("d:/dd.jpg");  
  FileInputStream fis = new FileInputStream(file);
        byte[] b = FileCopyUtils.copyToByteArray(fis);
        batisBlob.setContent(b);
        batisBlobDAO.insertIbaisBlob(batisBlob);
        fis.close();
        //****************插入图片结束*************
        //****************更新图片开始*************
        batisBlob.setId("1");
        batisBlob.setTitle("gengxin");
        File updateFile = new File("d:/dd.jpg");  
        FileInputStream updateFis = new FileInputStream(updateFile);
        byte[] ub = FileCopyUtils.copyToByteArray(updateFis);
        batisBlob.setContent(ub);
        batisBlobDAO.updateIbaisBlob(batisBlob);
        //****************更新图片结束*************
        //***************查询图片并输出************
        batisBlob.setId("1");
        batisBlob = batisBlobDAO.selectIbaisBlobById(batisBlob);
        byte[] bb = batisBlob.getContent();
        File outFile = new File("d:/cwb.jpg");  
        FileOutputStream sout = new FileOutputStream(outFile);
        sout.write(bb);
        sout.flush();
        sout.close();
        //***************查询图片并结束************
 }

}

说明:本类对BLOB字段的插入、修改、查询做了测试,无任何问题,均可以正确执行。

其中FileCopyUtils为Spring提供的工具类,它提供了许多一步式的静态操作方法,能够将文件内容拷贝到一个目标 byte[]、String 甚至一个输出流或输出文件中。使用起来十分方便。

你可能感兴趣的:(spring,bean,ibatis,String,Class,byte)