Ibatis + Spring 操作 Clob 详解

在我们公司,和别的部门做技术支持的过程中,在 Ibatis + Spring 的环境下,操作Oracle数据库CLOB字段的的时候,经常莫名其妙奇妙的出现奇怪的问题,现把出现的问题和解决的办法在下面一步一步列举出来:

一:Java工程环境介绍 

(1) 工程目录结构

 

目录结构

 

(2) Oracle9i + Oracle10g的驱动

 

(3) 用到的jar包如下:

 

jar包列表

 (4) 数据库表结构

create table IBATIS_CLOB
(
  ID      VARCHAR2(5) not null,
  TITLE   VARCHAR2(4000),
  CONTENT CLOB
)

二:主要代码如下:

(1) IbatisClob.java

  package cn.com.victorysoft.vo;
  public class IbatisClob {
   private String id;
   private String title;
   private String content;
   public String getId() {
      return id;
   }
   public void setId(String id) {
    this.id = id;
  }
  public String getContent() {
   return content;
  }
  public void setContent(String content) {
   this.content = content;
  }
  public String getTitle() {
   return title;
 }
  public void setTitle(String title) {
   this.title = title;
 }
}

(2) ibatisclob-sqlmap.xml

 

<?xml version = "1.0" encoding = "UTF-8"  ?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"  "
http://www.ibatis.com/dtd/sql-map-2.dtd"  >
<sqlMap namespace="ibatisclob">
 <typeAlias alias="ibatisclob" type="cn.com.victorysoft.vo.IbatisClob" />
 <select id="getIbatisClobById" parameterClass="ibatisclob" resultClass="ibatisclob">
  select * from IBATIS_CLOB where
  <dynamic prepend=" ">
  <isNotNull prepend="and" property="id">
     id = #id#
  </isNotNull>
  </dynamic>
 </select>

 <insert id="insert" parameterClass="ibatisclob">
  <selectKey resultClass="string" keyProperty="id">
   select IBATISCLOB_SQ.nextval as id from dual
  </selectKey>
  insert into IBATIS_CLOB(id,title,content) values(#id#,#title#,#content#)
 </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" /> 
 <sqlMap
  resource="cn/com/victorysoft/sqlmap/ibatisclob-sqlmap.xml" />
</sqlMapConfig>

(4) beans.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<?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:test</value>
    </property>
    <property name="username">
      <value>test</value>
    </property>
    <property name="password">
      <value>test</value>
    </property>
  </bean>
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
 <property name="configLocation" value="SqlMapConfig.xml"/>
 <property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataAccess" class="cn.com.victorysoft.dataaccess.impl.DataAccess">
   <property name="sqlMapClient" ref="sqlMapClient"/>
</bean>
<bean id="batisClobDAO" class="cn.com.victorysoft.dao.impl.IBatisClobDAOImpl">
   <property name="dataAccess" ref="dataAccess"/>
</bean>
</beans>

(5) 测试类代码 MainTest.java

package cn.com.victorysoft.test;

import java.sql.SQLException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.com.victorysoft.dao.IBatisClobDAO;
import cn.com.victorysoft.exception.IbatisClobException;
import cn.com.victorysoft.vo.IbatisClob;

public class MainTest {
 public static void main(String[] args) throws SQLException, IbatisClobException {
  ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
  IBatisClobDAO  batisClobDAO = (IBatisClobDAO)ctx.getBean("batisClobDAO");
  IbatisClob batisClob = new IbatisClob();
  StringBuffer sb = new StringBuffer("");
  for(int i=0;i<1005;i++){
   sb.append("a");
  }
  /*
   * 字段类型为varchar(4000)的话,插入的字符长度在1000-2000之间,或则汉语的长度在1000以上的时候经常会出现
   * 这样的错误:Cause: java.sql.SQLException: ORA-01461: 仅可以为插入 LONG 列的 LONG 值赋值
   * 解决方法:一是可以把该字段放到最后面,比如可以修改ibatisclob-sqlmap.xml,如下:
   * insert into IBATIS_CLOB(id,content,title) values(#id#,#content#,#title#)
   * 但是这样的话,会和CLOB类型冲突
   * 二是把varchar类型换成CLOB类型。
   *
   */
  batisClob.setTitle(sb.toString());
  StringBuffer str = new StringBuffer("");
  for(int i=0;i<1001;i++){
   str.append("a");
  }
  /*
   * 如果字段类型为CLOB的话,插入的字符或汉字的长度在1000以上也经常出现这样的错误:
   * Cause: java.sql.SQLException: ORA-01461: 仅可以为插入 LONG 列的 LONG 值赋值
   * 如果该字段是在插入的最后一列:如insert into IBATIS_CLOB(id,title,content) values(#id#,#title#,#content#)
   * 就没任何问题,如果是多个clob的话,都放后面也没问题。
   * 如果是更新语句的话,就把CLOB类型都放前面(网络上说的,没具体测试过)
   *
   */
  batisClob.setContent(str.toString());
  batisClobDAO.insertIbaisClob(batisClob);
 }

} 

注:通过改变字段的顺序来改变 ORA-01461: 仅可以为插入 LONG 列的 LONG 值赋值 的错误,并不是理想的解决办法。

三:彻底解决CLOB类型不会因为字段的顺序而出现ORA-01461: 仅可以为插入 LONG 列的 LONG 值赋值的错误。

(1)修改spring配置文件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: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="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="batisClobDAOSub" class="cn.com.victorysoft.dao.impl.IBatisClobDAOImpl">
   <property name="dataAccess" ref="dataAccess"/>
</bean>
<bean id="batisClobDAO" parent="transactionManagerRootProxy">
  <property name="target">
   <ref bean="batisClobDAOSub" />
  </property>
</bean>

</beans>

 说明:蓝色部分为事物配置,红色部分为CLOB配置。

A:如果对CLOB操作的类不放在事务的环境中,会报如下异常:

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

in iBATIS TypeHandlers that delegate to a Spring LobHandler

B:如果采用C3PO的数据源,nativeJdbcExtractor 这个bean要修改:

<bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.C3P0NativeJdbcExtractor" lazy-init="true" />

C:transactionManagerRootProxy bean 的 proxyTargetClass的设置

如果为TRUE的话,会采用 CGLIB代理,所以还要添加 cglib-2.1.3.jar 。如果设置为false的话,目标对象如果实现了接口Spring则会选择JDK动态代理,没实现接口,还是采用CGLIB代理。

(2) 修改 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="CLOB" javaType="java.lang.String" callback="org.springframework.orm.ibatis.support.ClobStringTypeHandler" />
 <sqlMap
  resource="cn/com/victorysoft/sqlmap/ibatisclob-sqlmap.xml" />
</sqlMapConfig>
(3)修改 ibatisclob-sqlmap.xml

<?xml version = "1.0" encoding = "UTF-8"  ?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"  "
http://www.ibatis.com/dtd/sql-map-2.dtd"  >
<sqlMap namespace="ibatisclob">
 <typeAlias alias="ibatisclob" type="cn.com.victorysoft.vo.IbatisClob" />
 <select id="getIbatisClobById" parameterClass="ibatisclob" resultClass="ibatisclob">
  select * from IBATIS_CLOB where
  <dynamic prepend=" ">
  <isNotNull prepend="and" property="id">
     id = #id#
  </isNotNull>
  </dynamic>
 </select>
 <insert id="insert" parameterClass="ibatisclob">
  <selectKey resultClass="string" keyProperty="id">
   select IBATISCLOB_SQ.nextval as id from dual
  </selectKey>
  insert into IBATIS_CLOB(id,content,title) values(#id#,#content:CLOB#,#title#)
 </insert>
</sqlMap>

 说明:必须强制为clob字段类型添加CLOB,如:content:CLOB。还必须是大写!如不加,默认的还是String类型,还是会报仅可以为插入 LONG 列的 LONG 值赋值的异常。切记!!

 

来源:http://blog.csdn.net/cwb1128/article/details/4339602

你可能感兴趣的:(spring,ibatis)