spring、Ibatis、mysql和java处理blob字段的方法是不同的,本文给出了处理过程的详细代码,现在一一开始介绍。
1)spring配置文件:
- <bean id="lobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler"/>
- <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
- <property name="configLocation" value="classpath:conf/sqlMapConfig.xml"></property>
- <property name="dataSource" ref="dataSource2"></property>
- <property name="lobHandler" ref="lobHandler"></property>
- </bean>
2)Ibatis配置文件:
- sqlMapConfig.xml:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
- "http://www.ibatis.com/dtd/sql-map-config-2.dtd">
- <sqlMapConfig>
- <properties resource="conf/serverity.properties" />
- <settings useStatementNamespaces="true" cacheModelsEnabled="false" maxRequests="256"
- maxSessions="64" maxTransactions="16"/>
- <typeHandler jdbcType="BLOB" javaType="[B"callback="org.springframework.orm.ibatis.support.BlobByteArrayTypeHandler"/>
- <sqlMap resource="conf/sqlmap/monitorSqlMap.xml" />
- </sqlMapConfig>
- monitorSqlMap.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="favMonitor">
- <select id="queryVoBytes" parameterClass="java.util.Map" resultClass="[B">
- select voListBytes from t_favMonitor where userId=#userId# and reqName=#reqName#
- </select>
- </sqlMap>
3) mysql数据库:
- table: t_favMonitor(userid int, reqName varchar, voListBytes blob)
4) java存取:
- private static class ByteObjectUtil{
- static byte[] convertObj2ByteArray(Object obj) throws IOException{
- ByteArrayOutputStream baos=null;
- ObjectOutputStream oos=null;
- try {
- baos=new ByteArrayOutputStream();
- oos=new ObjectOutputStream(baos);
- oos.writeObject(obj);
- return baos.toByteArray();
- } catch (IOException e) {
- throw new IOException(e);
- }finally{
- baos.close();
- oos.close();
- }
- }
- static Object readObjFromByteArray(byte[] ob) throws IllegalStateException, IOException, ClassNotFoundException{
- if(ob==null||ob.length==0)
- throw new IllegalStateException("parameter byte[] ob is empty!");
- ByteArrayInputStream bais=new ByteArrayInputStream(ob);
- ObjectInputStream ois=null;
- try {
- ois=new ObjectInputStream(bais);
- return ois.readObject();
- } catch (IOException e) {
- throw new IOException(e);
- }finally{
- bais.close();
- ois.close();
- }
- }
- }
关于处理blob字段的方法就介绍到这里,如果您想了解更多数据库方面的知识,可以到这里看一看:http://database.51cto.com/,谢谢各位的支持。
【编辑推荐】