接上一篇:http://lz726.iteye.com/blog/1882265
开发架构是struts+spring的。 DAO层就是用spring的jdbctemplate
大对象用了LobHandler,用这个东西问题也蛮多。
因为附件大小没有做限制,可能很大,所以采取流的方式。但是LobHandler 处理流的方式,网络上都找不到例子,就算找到了,也是不能用的,头大了。
界面上传进来的流,不懂为什么不能直接用LobHandler 入库,最后做了转换可以实现。代码如下:
final InputStream stream=(InputStream)cform.getValue("stream");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes =new byte[10240];
int length=0;
while ((length = stream.read(bytes)) != -1) {
baos.write(bytes, 0, length);
}
baos.flush();
final InputStream bais=new ByteArrayInputStream(baos.toByteArray());
ireturn=jdbcTemplate.execute(sql.toString(),new AbstractLobCreatingPreparedStatementCallback(lobHandler){
protected void setValues(PreparedStatement pstmt,LobCreator lobCreator){
try {
pstmt.setString(1, id);
lobCreator.setBlobAsBinaryStream(pstmt,7,bais,bais.available());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
配置
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler" lazy-init="true"> </bean>
直接读取文件的,就可以。
final File file = new File("d:\\a.jpg");
LobHandler lobHandler = new DefaultLobHandler();
final InputStream input = new FileInputStream(file);
final String filesize=String.valueOf(file.length());
ireturn=jdbcTemplate.execute(sql.toString(),new AbstractLobCreatingPreparedStatementCallback(lobHandler){
protected void setValues(PreparedStatement pstmt,LobCreator lobCreator){
try {
pstmt.setString(1, id);
lobCreator.setBlobAsBinaryStream(pstmt,7,input,(int)file.length());
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
现在还不知道,在不同中间件下是否有问题,是否支持tomcat以外的,开发环境是tomcat的没问题。
现在想来,所有问题都是可以解决的,只要是问题。相信吧~