Hibernate4 clob字段存取

时间:2020-12-06 06:19:41

domain的字段:    

private Clob content;

hibernate的xml映射

 <property name="content" type="clob">
<column name="CONTENT" >
<comment>内容</comment>
</column>
</property>

首先是保存:

  

LobHelper lobHelper = session.getLobHelper();
Clob clob = lobHelper.createClob(content);
news.setContent(clob);

content是前台传递的内容。这样我们就可以保存这个对象了。

下面是读取:

  

News news = newsDAO.get(id);
Clob clob = news.getContent();
return StringUtils.clobToString(clob);

我们查询到对应的对象,然后获取到clob,然后传入一个静态方法,从而得到字符串。

该静态方法的代码如下:

 public static String clobToString(Clob clob) {
String reString = "";
Reader is = null;
try {
is = clob.getCharacterStream();
} catch (SQLException e) {
e.printStackTrace();
}
// 得到流
BufferedReader br = new BufferedReader(is);
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
StringBuffer sb = new StringBuffer();
while (s != null) {
//执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
sb.append(s);
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
reString = sb.toString();
return reString;
}

结束。