最近在项目上要用Mybatis来操作XMLType,经历了种种坎坷,目前还在调研中,先记下一些问题
1. 首先,得到消息是使用Mybatis来操作CLOB数据
翻阅了一下文档,问题非常好解决,利用Mybatis的TypeHandler,重新做了一下处理,就把一个InputStream对象插入到了Oracle数据库中
主要涉及文件,大体上就三个:Mybatis自己的配置文件(Config.xml/Mybatis-config.xml);作转换处理的java类;映射的写sql的xxxMapper.xml
首先,我们要在Config.xml中描述自己用来处理转换的Handler:在这里建立了两个处理类,第二个就是用来将Inputstream类型转换成CLOB的
<configuration>
<typeAliases>
<typeAlias alias="User" type="xx.ssaa.test.model.User"/>
<typeAlias alias="User_Oracle" type="xx.ssaa.test.UserOracle"/>
</typeAliases>
<typeHandlers>
<typeHandler javaType="String" jdbcType="INTEGER" handler="xx.ssaa.test.TestChangeHandler" />
<typeHandler javaType="java.io.InputStream" jdbcType="CLOB" handler="xx.ssaa.test.TestFileToClobHandler" />
</typeHandlers>
接着,我们创建指定的处理类:TestFileToClobHandler,注意路径要和前面的包名一致(xx.ssaa.test)
我只需要插入,所以只要在最后的方法内,转换一下将InputStream转成Reader插入即可。
public class TestFileToBlobHandler implements TypeHandler {
@Override
public Object getResult(ResultSet arg0, String arg1) throws SQLException {
<pre name="code" class="java"><span style="white-space:pre"> </span>// TODO Auto-generated method stub
return null;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>@Override
public Object getResult(ResultSet arg0, int arg1) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public Object getResult(CallableStatement arg0, int arg1)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
<span style="white-space:pre"> </span>@Override
public void setParameter(PreparedStatement arg0, int arg1, Object arg2,
JdbcType arg3) throws SQLException {
File xfile = (File) arg2;
StringBuffer sbInput = new StringBuffer();
String line = null;
try {
InputStream input = new FileInputStream(xfile);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
<span style="white-space:pre"> </span>} catch (Exception ex) {
ex.printStackTrace();
}
arg0.setClob(arg1, reader);
<span style="white-space:pre"> </span>}
}