最近一个项目中有一部分是新闻管理,其中新闻的内容在数据库中的类型是varchar2,此类型最大容量是4000byte,而用户需要输入更多的字节,所以不得不将其改大,方法是将它的类型由varchar2改成Clob,这样我们的代码也要修改
第一:在News实体News.java文件中新增如下代码
private Clob newContentClob;//2010-08-25
public Clob getNewContentClob() {
return newContentClob;
}
public void setNewContentClob(Clob newContentClob) {
this.newContentClob = newContentClob;
}
第二:修改配置文件News.hbm.xml---此步是映射关系的对应
<property name="newContentClob">
<column name="new_content" sql-type="clob"/>
</property>
第三:修改原来的新增新闻、修改新闻方法 将String转换成Clob存入数据库
public void save(News news)
{
try {
Session session = getSession();
// 初始化SummaryClob字段
oracle.sql.CLOB clob = oracle.sql.CLOB.empty_lob();
news.setNewContentClob(clob);
session.save(news);
session.flush();
// 此处一定要用lockMode.UPGRADE模式进行锁定刷新
session.refresh(news, LockMode.UPGRADE);
// 获取MeetingHead实体的SummaryClobString属性值
String content = news.getNewContent();
// 将获取的辅助字段的值通过oracle.sql.CLOB的putString()方法赋
// 值给实体内的summaryClob字段
org.hibernate.lob.SerializableClob sclob = (org.hibernate.lob.SerializableClob) news
.getNewContentClob();
clob = (oracle.sql.CLOB) sclob.getWrappedClob();
clob.putString(1, content);
} catch (SQLException e) {
e.printStackTrace();
}
// getHibernateTemplate().save(news);原代码就是这一行
}
第四:红色部分为新增的代码,目的是将数据库查处的Content(类型为Clob)转换成String显示在页面上
public News findNewsById(Integer id) throws AegeanException
{
try
{
News news = newsDao.get(id);
if (news != null)
{
java.sql.Clob clob = news.getNewContentClob();
if (clob != null)
{
news.setNewContent(clob.getSubString(1,(int) clob.length()));
}
return news;
}
return news;
}
catch (Exception e)
{
log.debug(e.getMessage());
throw new AegeanException("error");
}
}
public List<News> findNewsByPage(Pager pager) throws AegeanException {
try {
List<News> list = newsDao.findbyPage(pager);
if (list != null && !list.isEmpty())
{
List<News> newList = new ArrayList<News>();
Iterator<News> iterator = list.iterator();
while (iterator.hasNext())
{
News news = iterator.next();
java.sql.Clob clob = news.getNewContentClob();
if (clob != null)
{
news.setNewContent(clob.getSubString(1, (int) clob.length()));
}
newList.add(news);
}
return list;
}
return list;
} catch (Exception e) {
log.debug(e.getMessage());
throw new AegeanException("error");
}
}