使用场景:有的时候我么你在存取内容时,可能存的内容值过大,而oracle中varchar2最大长度为4000字节,所以这时我们需要使用到大字段。
接下来我们来开始使用大字段。
首先给出一种blob在hibernate中的使用情况
1.表结构
2.java实体类
/**
*数据库大字段内容
*/
private Blob blobContent;
blobContent字段直接配成Blob类型的。
3.映射文件
<property name="blobContent" column="blobContent" type="java.sql.Blob" />
4.字段使用
需要使用就需要转换,我们在存的时候把字符串转换成Blob,在读取的时候把Blob转化成String
public class BlobToString {
@SuppressWarnings("unused")
private static Logger logger = Logger.getLogger(BlobToString.class);
/*
*blob转化成String
*/
public static String convertBlobToString(Blob blob) throws GameCMSContentException{
SerializableBlob sb = (SerializableBlob)blob;
if(sb==null){
return null;
}
BLOB blobOracle = (BLOB) sb.getWrappedBlob();
if(blobOracle==null){
return null;
}
InputStream is;
String context="";
try {
is = blobOracle.getBinaryStream();
int length = (int) blobOracle.length();
byte[] data = new byte[length];
if(is==null){
return null;
}
is.read(data);
is.close();
context=new String(data,"utf-8").trim();
} catch (SQLException e) {
throw new GameCMSContentException(null,"获取内容转化成字符串异常!");
} catch (IOException e) {
throw new GameCMSContentException(null,"获取内容转化成字符串异常!");
}
return context;
}
/*
*String 转化成 Blob
*/
public static Blob convertStringToBlob(String content) throws GameCMSContentException{
Blob blob = null;
byte[] bytes_content = content.getBytes();
ByteArrayInputStream bi = new ByteArrayInputStream(bytes_content);
try {
blob = Hibernate.createBlob(bi);
} catch (IOException e) {
throw new GameCMSContentException(null,"封装内容转化成大字段异常!");
}
return blob;
}
}
好了,到目前为止我们使用Blob完整的例子已经做完,大家可以尝试下。
但是,请大家注意了上面的例子只能用在hibernate3.5以下的版本。如果用3.5以上版本则会报转化错误。原因是3.5以上版本对Blob类型进行了改造。
那么如果引用hibernate3.5以上版本怎么使用那?
这里在提供另外例子
1.首先改造实体类
/**
*数据库大字段内容
*/
private byte[] blobContent;
字段用字节数组来实现。
2.改造映射文件
<property name="blobContent" column="blobContent" type="org.springframework.orm.hibernate3.support.BlobByteArrayType" />
3.改造读取方式
public class BlobToString {
@SuppressWarnings("unused")
private static Logger logger = Logger.getLogger(BlobToString.class);
/*
*blob转化成String
*/
public static String convertBlobToString(byte[] content) throws GameCMSContentException{
String result = "";
ByteArrayInputStream msgContent = new ByteArrayInputStream(content);
byte[] byte_data = new byte[msgContent.available()];
msgContent.read(byte_data, 0,byte_data.length);
result = new String(byte_data);
return result;
}
/*
*String 转化成 Blob
*/
public static byte[] convertStringToBlob(String content) throws GameCMSContentException{
if(content == null){
return null;
}
byte[] bytes_content = content.getBytes();
return bytes_content;
}
}
这样我们就可以使用了。想必大家也看出来,我们把Blob类型转化成byte[],然后读取字节数组输入流。